Update record with previous row

后端 未结 2 395
北海茫月
北海茫月 2020-12-07 00:13

I have a situation where I need to update the records with previous row value.

Source:

|MatId | BaseId |Flag|Pkg1| CS1
-----------------------------         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 00:48

    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
    

提交回复
热议问题