简体   繁体   中英

Updating start time of next row to the end date of the previous row

I have a table:

locid   timestart      timeend
1       Jan 23 2015    Dec-31-9999
1       Feb 15 2015    Dec-31-9999
2       Mar 18 2015    Apr-28-2015
2       Nov 23 2015    Dec-31-9999
2       Jul 23 2015    Nov-23-2015
2       Apr 28 2015    Dec-31-9999

The time end is incorrect in the above table. It should be like below

locid   timestart      timeend
1       Jan 23 2015    feb-15-2015
1       Feb 15 2015    Dec-31-9999
2       Mar 18 2015    Apr-28-2015
2       Nov 23 2015    Jul-23-2015
2       Jul 23 2015    Nov-23-2015
2       Apr 28 2015    Dec-31-2015

How write SQL to correct the time end from table 1 as shown in table 2?

You want the timestart of the next row:

WITH newTable AS
(SELECT 8, LEAD(timestart,1,'99991231') OVER (PARTITON BY locid ORDER BY timestart) AS newTimeEnd
FROM theTable
)
UPDATE newTable SET timeend = newTimeEnd;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM