2017-08-02 6 views
0

私は、いくつかのユニットの期間が重複しているテーブルを持っています。各ユニットについて、時間的オーバーラップの開始時と終了時に時間を分割したいと思います。国-期間とpostgresql:オーバーラップ時の分割時間

例:

cntry  | startdate | enddate | 

A   | 1960-01-01 | 1989-12-31 | 

B   | 1955-01-01 | 1974-12-31 | 
B   | 1975-01-01 | 1999-12-31 | 

所望の出力:

cntry  | startdate | enddate | 

A   | 1960-01-01 | 1974-12-31 | 
A   | 1975-01-01 | 1989-12-31 | 

B   | 1955-01-01 | 1959-12-31 | 
B   | 1960-01-01 | 1974-12-31 | 
B   | 1975-01-01 | 1999-12-31 | 

また、これは私が以前に尋ねたquestionに密接に関連して明確化

のために、ここで、このillustrationを参照してください、しかし、そこで使用されているソリューションでは解決できませんでした。この場合の最良のアプローチとなるコメントや提案は大歓迎です!

答えて

0

再帰的なCTEを使用すると、間隔を分割し、間隔をさらに分割することができます。ここでは、指定されたデータで動作する例を示します。ハックのビットなので、それを洗練させたいかもしれません。

with cuts as (
    select startdate as cut_date from country 
    ), 
cntry_cuts as (
    select * from country where 1=0 
    union 
    select * from (
     select cntry, startdate, cast(cuts.cut_date - interval '1 day' as date) as enddate 
     from 
      country as c 
      cross join cuts 
      where cuts.cut_date > startdate and cuts.cut_date < enddate 
     union 
     select cntry, cuts.cut_date as startdate, enddate 
     from country as c 
     cross join cuts 
      where cuts.cut_date > startdate and cuts.cut_date < enddate 
     union 
     select cntry, startdate, enddate 
     from country as c cross join cuts 
     where (select max(cut_date) from cuts) < enddate 
     ) as x 
    ) 
select cntry, startdate, min(enddate) 
from cntry_cuts 
group by cntry, startdate 
order by cntry, startdate; 

再帰的なCTEの最初の非再帰的な部分は、出力形式の確立にのみ使用されることに注意してください。元のデータは出力フォーマットに追加されないので、条件はWHERE 1=0です。

関連する問題