Exercise · SQL & Querying
Predict, then run it
Predict the output
bk(s, e) = (1,9),(2,3),(8,10) — the (2,3) booking is contained in (1,9). Merge the overlapping ranges with the running-max frontier:
WITH f AS (SELECT s, e, MAX(e) OVER (ORDER BY s ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prev_max FROM bk), g AS (SELECT s, e, SUM(CASE WHEN prev_max IS NULL OR s > prev_max THEN 1 ELSE 0 END) OVER (ORDER BY s) AS island FROM f) SELECT MIN(s) AS start, MAX(e) AS end FROM g GROUP BY island ORDER BY start;
Predict the exact output.