2017-08-02 87 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 | 

也看到這個illustration這裏澄清

這是密切相關的一個question我剛纔問的,但用那裏使用的解決方案無法解決。對於這種情況下的最佳方法的任何意見或建議將非常歡迎!

回答

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條件。