Update record with previous row

谁都会走 提交于 2019-11-28 02:23:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!