4

I have a table [RoleHistories] table with columns:

[RoleHistoryId] [PersonId] [Start] [End]

The Start column is populated with a date. The end column is null. There are multiple rows per person. I need to update the end column to have a date that is the start date of the next record. If there is no subsequent record the end should remain null

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

I would want

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
4

1 回答 1

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
于 2013-06-10T16:19:07.147 回答