我有一个表[RoleHistories]
表,其中包含列:
[RoleHistoryId] [PersonId] [开始] [结束]
“开始”列中填充了日期。结束列为空。每个人有多行。我需要更新结束列以使日期为下一条记录的开始日期。如果没有后续记录,则结尾应保持为空
E.g。
RoleHistoryId = 999, PersonId =1, Start=2009-1-1, End=null
RoleHistoryId = 2677, PersonId =1, Start=2011-5-1, End=null
RoleHistoryId = 4637, PersonId =1, Start=2013-9-1, End=null
我想要
RoleHistoryId = 999, PersonId =1, Start=2009-1-1, End=2011-5-1
RoleHistoryId = 2677, PersonId =1, Start=2011-5-1, End=2013-9-1
RoleHistoryId = 4637, PersonId =1, Start=2013-9-1, End=null
答案 0 :(得分:4)
UPDATE rh1
SET End = (SELECT Min(Start)
FROM RoleHistories rh2
WHERE rh1.Personid = rh2.Personid
AND rh1.Start < rh2.Start)
FROM RoleHistories rh1
WHERE End IS NULL