2017-09-13 156 views
1

此示例比根據新記錄的開始日期更新先前記錄有點棘手。我希望你能幫忙。更新以前行的開始日期和結束日期

ID 1000(有很多ID,我們需要分區?)有一個初始開始日期。

該ID被鏈接到另一個合同。因此,第一份合同的結束日期是第二份合同的開始日期。請注意,第二份合同可能會或可能不會有未來的日期。

但是,在第二份合同開始前,ID可能會鏈接到不同的合同。所以第二份合同變得無效。第三份合同現在優先,第一份合同的結束日期需要更改爲第三份合同的開始日期。第二份合同保持顯示開始和結束日期相同。

有關如何使用T-SQL實現此目的的任何想法?

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 

在此先感謝您。

親切的問候 d

+0

什麼版本的SQL Server? – scsimon

+0

Hi Scsimon,這是SQL 2014. – user3497385

回答

1

這適用於樣本數據,但是如果有可能超過1組的合同,這將是無效連續會失敗。

declare @table table (id int, contract int, StartDate date, EndDate date) 
insert into @table 
values 
(1000,1,'20170831',NULL), 
(1000,2,'20170916',NULL), 
(1000,3,'20170914',NULL) 

;with cte as(
select 
    id 
    ,contract 
    ,StartDate 
    ,EndDate 
    ,NewEndDate = case when StartDate > lead(StartDate) over (partition by id order by contract) then StartDate else lead(StartDate) over (partition by id order by contract) end 
from @table t), 

cte2 as(
select 
    id 
    ,contract 
    ,StartDate 
    ,EndDate 
    ,NewEndDate = case when NewEndDate = Lead(NewEndDate) over (partition by id order by contract) then Lead(StartDate,2) over (partition by id order by contract) else NewEndDate end 
from 
    cte 
) 


update cte2 
set EndDate = NewEndDate 

select * from @table 

編輯成一排99無效

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 
+0

謝謝:)可以有超過1個合同無效。 – user3497385

+0

所以你甚至可以有2或3行,例如成爲無效。正如你所提到的那樣,鉛會失敗。 – user3497385

+0

好吧,你能提供更好的樣本數據嗎?爲什麼不只是添加一個列無效/有效的標誌?對於像這樣的東西,這很常見。 – scsimon

相關問題