postgresql:分割重叠时间段

问题描述:

我有一个表的重叠时间段为多个单元。对于每个单位,我想在每个时间重叠的开始和结束时分开时间段。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我刚才问的,但用那里使用的解决方案无法解决。对于这种情况下的最佳方法的任何意见或建议将非常欢迎!

递归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条件。