简体   繁体   English

Postgres 分割重叠日期范围的最有效方法

[英]Postgres most efficient way to split overlapping daterange

For example I have following entities in table A:例如,我在表 A 中有以下实体:

entityId, metaData, startDate, endDate
Row 1: 1, some content, 2021-01-01, 2022-01-01
Row 2: 1, some content 2, 2022-01-02, 9999-12-31

And I have following entities in table B:我在表 B 中有以下实体:

entityId, metaData, startDate, endDate
Row 1: 1, overlapping content, 2021-08-12, 2022-01-01
Row 2: 1, overlapping content 2, 2022-03-01, 2023-01-01
Row 3: 1, overlapping content 3, 2023-01-02, 9999-12-31
|-----------ROW 1 (A)-----------| |-----------ROW 2 (A)------------| 
        |-------ROW 1 (B)-------|   |--ROW 2 (B)--|  |--ROW 3 (B)--|

As output I want to split rows from A by overlapping with rows from B (using entityId key):作为输出,我想通过与 B 中的行重叠来分割 A 中的行(使用 entityId 键):

Row 1 (A): 1, some content, 2021-01-01, 2021-08-11
Row 1 (B): 1, overlapping content, 2021-08-12, 2021-12-31
Row 2 (A): 1, some content 2, 2022-01-02, 2022-02-28
Row 2 (B): 1, overlapping content 2, 2022-03-01, 2023-01-01
Row 3 (B): 1, overlapping content 3, 2023-01-02, 9999-12-31

Does smth like this fit your needs?像这样的东西是否符合您的需求?

with cte as
(
    select * from table_a
    union all
    select * from table_b
)
select
       entityid,
       metadata,
       startdate,
       coalesce(
           ((lead(startdate) over (order by startdate)) - INTERVAL '1 DAY') :: DATE,
           enddate
       )
from cte order by startdate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM