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