2017-09-13 10 views
1

この例は、新しいレコードの開始日に基づいて前のレコードを更新するだけの場合よりも少し面倒です。私はあなたが助けてくれることを望んでいました。前の行の開始日と終了日の更新

ID 1000(多くのIDがあり、パーティション化する必要がありますか?)は、最初の開始日があります。

IDは別の契約にリンクされます。したがって、第1契約の終了日は、第2契約の開始日です。 2番目の契約は、将来の日付である場合とそうでない場合があります。

ただし、2番目の契約が開始される前に別の契約にリンクされている可能性があります。したがって、2番目の契約は無効となります。 3番目の契約が今すぐ優先され、最初の契約の終了日を3番目の契約の開始日に変更する必要があります。 2番目の契約は開始日と終了日が同じであることを示しています。

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

こんにちは、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 

ROW 99無効とFOR EDIT

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

ありがとうございました:)ヌルとボイドの2つ以上の契約があります。 – user3497385

+0

したがって、空白になる2行または3行などもあります。あなたが言及したように、鉛は失敗するでしょう。 – user3497385

+0

よく、より良いサンプルデータを提供できますか?列に空白/アクティブフラグを追加するだけではどうですか?このようなものにはかなり一般的です。 – scsimon

関連する問題