两个表之间的交叉间隔日期

时间:2016-12-19 10:46:08

标签: postgresql postgresql-9.2

您好我需要将两个具有间隔日期的表交叉

时间表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

时间表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

这是我试过的SQL:

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

需要这样的结果:

总计:00:60:00

enter image description here

1 个答案:

答案 0 :(得分:3)

使用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)    

间隔总和:

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)