2017-09-13 151 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

相关问题