该示例比仅根据新记录的开始日期更新先前的记录要复杂一些。我希望您能提供帮助。
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
这适用于示例数据,但是如果可能存在多个合同,并且合同中的空合同无效 ,则 合同将失败。
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个NULL并作废
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