Merge Overlapping Intervals Running MAX

Collapse overlapping shift records into merged spans by sorting on start and tracking the running maximum end with a window function frame.

SqlData Integrity

Code

snippet
WITH shifts (id, worker, start_ts, end_ts) AS (
    VALUES
        (1, 'ada', TIMESTAMPTZ '2026-06-01 08:00', TIMESTAMPTZ '2026-06-01 10:30'),
        (2, 'ada', TIMESTAMPTZ '2026-06-01 10:00', TIMESTAMPTZ '2026-06-01 12:00'),
        (3, 'ada', TIMESTAMPTZ '2026-06-01 12:30', TIMESTAMPTZ '2026-06-01 13:30'),
        (4, 'ada', TIMESTAMPTZ '2026-06-01 13:15', TIMESTAMPTZ '2026-06-01 14:00'),
        (5, 'lee', TIMESTAMPTZ '2026-06-01 09:00', TIMESTAMPTZ '2026-06-01 09:45')
),
ordered AS (
    SELECT
        id, worker, start_ts, end_ts,
        -- running max of every end seen BEFORE this row: a wide earlier
        -- interval keeps covering later ones
        COALESCE(
            MAX(end_ts) OVER (PARTITION BY worker ORDER BY start_ts, id
                              ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING),
            '-infinity'::timestamptz
        ) AS covered_through
),
grouped AS (
    SELECT
        id, worker, start_ts, end_ts,
        SUM(CASE WHEN start_ts <= covered_through THEN 0 ELSE 1 END)
            OVER (PARTITION BY worker ORDER BY start_ts, id
                  ROWS UNBOUNDED PRECEDING) AS span_no
    FROM ordered
)
SELECT worker, span_no,
       MIN(start_ts) AS merged_start,
       MAX(end_ts)   AS merged_end,
       COUNT(*)      AS merged_shifts
FROM grouped
GROUP BY worker, span_no
ORDER BY worker, merged_start;

Following the execution — Merge Overlapping Intervals Running MAX

The statement is SELECT; the script has no base tables — three CTEs (shifts seeded from VALUES, ordered, grouped) chain together, and the final query reads grouped.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, SUM, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) evaluating each row against a peer set instead of folding rows into one; an ORDER BY that fixes the output order.

Points of care

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

Run the final SELECT against the CTE grouped — shifts and ordered are upstream CTEs in the same WITH, not tables.

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `ordered`, `grouped`.