1
由于SQL Server 2008的兼容性问题,我试图实现下面的结果,但没有ROWS BETWEEN
函数。您的帮助将不胜感激。更新以前行的开始日期和结束日期(无ROWS BETWEEN)
这是一个重新的
updating start and end dates of previous rows
id contract Start Date End Date
-------------------------------------------
1000 1 2017/08/31 9999/12/31
id contract Start Date End Date
-------------------------------------------
1000 1 2017/08/31 2017/09/16
1000 2 2017/09/16 9999/12/31
id contract Start Date End Date
-------------------------------------------
1000 1 2017/08/31 2017/09/14
1000 2 2017/09/16 2017/09/16
1000 3 2017/09/14 9999/12/31
解决方案:
declare @table table (id int, contract int, StartDate date, EndDate date)
insert into @table
values (1000, 1, '20170831', NULL),
(1000, 2, '20170916', NULL),
(1000, 2, '20170915', NULL),
(1000, 3, '20170914', NULL)
;with cte as
(
select
id, contract,
StartDate, EndDate,
NewEndDate = min(StartDate) over (partition by id order by contract ROWS BETWEEN 1 FOLLOWING AND 99 FOLLOWING)
from
@table
), cte2 as
(
select
id, contract,
StartDate, EndDate,
NewEndDate = isnull(case when NewEndDate = lag(NewEndDate) over (partition by id order by contract) then StartDate else NewEndDate end, '99991231')
from
cte
)
update cte2
set EndDate = NewEndDate
select * from @table
亲切的问候 d