Join overlapping date ranges

前端 未结 4 1390
半阙折子戏
半阙折子戏 2021-02-08 06:16

I need to join table A and table B to create table C.

Table A and Table B store status flags for the IDs. The status flags (A_Flag and B_Flag) can change from time to ti

4条回答
  •  死守一世寂寞
    2021-02-08 06:27

    I'm going to solve this in SQL, assuming that you have a function called lag (SQL Server 2012, Oracle, Postgres, DB2). You can get the same effect with a correlated subquery.

    The idea is to get all the different time periods. Then join back to the original tables to get the flags.

    I am having trouble uploading the code, but can get most of it. However, it starts with start ends, which you create by doing a union (not union all) of the four dates in one column: select a.start as thedate. This is then union'ed with a.end, b.start, and b.end.

    with driver as (
        select thedate as start, lag(thedate) over (order by thedate) as end
        from startends
       ) 
    
    select startdate, enddate, a.flag, b.flag
    from  driver left outer join
         a
         on a.start >= driver.start and a.end <= driver.end left outer join
         b
         on b.start >= driver.start and b.end <= driver.end
    

提交回复
热议问题