Search code examples
postgresqlaggregate-functionspostgresql-9.2

intersection interval dates between two tables


Hello I need to intersect two tables with interval dates

Timeline 1

start               | end
---------------------------------------------
2016-12-19 08:00:00 | 2016-12-19 08:30:00
2016-12-19 09:30:00 | 2016-12-19 11:00:00

Timeline 2

start               | end
---------------------------------------------
2016-12-19 08:30:00 | 2016-12-19 10:00:00
2016-12-19 10:30:00 | 2016-12-19 11:00:00

here's SQL i tried:

SELECT * FROM start, end FROM timeline1 
INTERSECT
SELECT * FROM start, end FROM timeline2 

need result like this:

Total: 00:60:00

enter image description here


Solution

  • Use range operators * and &&:

    select tsrange(t1."start", t1."end") * tsrange(t2."start", t2."end") as "intersections"
    from timeline1 t1
    join timeline2 t2 
    on tsrange(t1."start", t1."end") && tsrange(t2."start", t2."end");
    
                     intersections                  
    -----------------------------------------------
     ["2016-12-19 09:30:00","2016-12-19 10:00:00")
     ["2016-12-19 10:30:00","2016-12-19 11:00:00")
    (2 rows)    
    

    Sum of intervals:

    select sum(upper("intersections")- lower("intersections")) as total
    from (
        select tsrange(t1."start", t1."end") * tsrange(t2."start", t2."end") as "intersections"
        from timeline1 t1
        join timeline2 t2 
        on tsrange(t1."start", t1."end") && tsrange(t2."start", t2."end")
    ) s
    
      total   
    ----------
     01:00:00
    (1 row)