The idea is to model the algorithm for scanning merge intervals. My solution ensures that it works across a wide range of SQL implementations. I tested it on MySQL, Postgres, SQL-Server 2017, SQLite and even Hive.
It is assumed that the table layout is as follows.
CREATE TABLE t ( a DATETIME, b DATETIME );
We also assume that the interval is half open, as [a, b).
When (a, i, j) is in the table, it shows that there are j intervals covering a, and I are intervals covering the previous point.
CREATE VIEW r AS SELECT a, Sum(d) OVER (ORDER BY a ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS i, Sum(d) OVER (ORDER BY a ROWS UNBOUNDED PRECEDING) AS j FROM (SELECT a, Sum(d) AS d FROM (SELECT a, 1 AS d FROM t UNION ALL SELECT b, -1 AS d FROM t) e GROUP BY a) f;
We produce all the endpoints in the union of the intervals and connect the neighboring ones. Finally, we produce a set of intervals, selecting only odd lines.
SELECT a, b FROM (SELECT a, Lead(a) OVER (ORDER BY a) AS b, Row_number() OVER (ORDER BY a) AS n FROM r WHERE j=0 OR i=0 OR i is null) e WHERE n%2 = 1;
I created a sample DB-Fiddle and SQL-Fiddle . I also wrote a blog post about join intervals in SQL .
Chao xu
source share