I have a situation where I need to update the records with previous row value.
Source:
|MatId | BaseId |Flag|Pkg1| CS1
--------------------------------
|3001 | 3001 | 1 | 20 | 2 |
|3002 | 3001 | 0 | 15 | 3 |
|3003 | 3001 | 0 | 10 | 4 |
Here both 3001 (MatID
) and 3001(BaseID
) are same so FLAG
=1, in the next record only BASEID
is same. The output should be only PKG1
field updated with the current row value.
Target or output:
|MatId | BaseId|Flag|Pkg1|CS1
------------------------------
|3001 | 3001 | 1 | 20 | 2|
|3002 | 3001 | 0 | 20 | 3|
|3003 | 3001 | 0 | 20 | 4|
As seen in the target above i have to update the two values in PKG1 with the value from first record 20. Also there are many columns with Pkg1, how to update all the columns with a single query?
Any help is very much appreciated.
Thanks.
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.
来源:https://stackoverflow.com/questions/33402252/update-record-with-previous-row