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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With