I have a situation where I need to update the records with previous row value.
Source:
|MatId | BaseId |Flag|Pkg1| CS1
-----------------------------
To get Previous and Next value with the help of LEAD and LAG Function in SQL Server is very simple. If you are using an earlier version of SQL Server than 2012 which does not support LEAD
and LAG
function we can use ROW_NUMBER()
.
Try to use something like this:
;WITH t AS
(
select LAG(MatId) OVER (ORDER BY MatId) AS previousMatId
, BaseId
, MatId
from TABLE
)
update tab
set tab.Pkg1 = p.Pkg1
from TABLE tab
inner join t on tab.MatId = t.MatId and t.BaseId = t.previousMatId
left join (select MatId AS MatId
, ISNULL(LAG(Pkg1) OVER (ORDER BY MatId), Pkg1) AS Pkg1
from TABLE) p on t.MatId = p.MatId
Are you saying the newer mats need to be updated with the Pkg1 belonging to the original mat? If so it would be:
update NewMats
set NewMats.Pkg1 = Base.Pkg1
from MyTabe as NewMats
inner join (select BaseId, Pkg1
from MyTable
where BaseId = MatId) as Base
on Base.BaseId = NewMats.BaseId
where NewMats.BaseId < NewMats.MatId
But if this is the case, then your data model needs to be changed. The rule is that a given piece of information should live in only one place. So maybe break this out into 2 tables that are related.