22,206
社区成员
发帖
与我相关
我的任务
分享
declare @t table(startdate datetime,sumdate datetime )
insert into @t select '2015-01-01 20:00:00' ,'2015-01-01 20:00:00'
insert into @t select '2015-01-02 21:00:00' ,null
insert into @t select '2015-01-03 23:00:00' ,'2015-01-03 20:00:00'
insert into @t select '2015-01-04 01:00:00' ,null
insert into @t select '2015-01-05 05:00:00' ,null
insert into @t select '2015-01-06 08:00:00' ,'2015-01-06 20:00:00'
insert into @t select '2015-01-07 15:00:00' ,null
insert into @t select '2015-01-08 08:00:00' ,null
;
with ta
as
(
select row_number()over(order by startdate) as orderid,* from @t)
select *,case when sumdate is null then (select max(sumdate) from ta where orderid < a.orderid ) else sumdate end
from ta a
orderid startdate sumdate
-------------------- ----------------------- ----------------------- -----------------------
1 2015-01-01 20:00:00.000 2015-01-01 20:00:00.000 2015-01-01 20:00:00.000
2 2015-01-02 21:00:00.000 NULL 2015-01-01 20:00:00.000
3 2015-01-03 23:00:00.000 2015-01-03 20:00:00.000 2015-01-03 20:00:00.000
4 2015-01-04 01:00:00.000 NULL 2015-01-03 20:00:00.000
5 2015-01-05 05:00:00.000 NULL 2015-01-03 20:00:00.000
6 2015-01-06 08:00:00.000 2015-01-06 20:00:00.000 2015-01-06 20:00:00.000
7 2015-01-07 15:00:00.000 NULL 2015-01-06 20:00:00.000
8 2015-01-08 08:00:00.000 NULL 2015-01-06 20:00:00.000