Skip to content
BytePatterns

Collapse a Status Log Into Runs

HardSQL#gaps-and-islands#window-function#row-number~35m

Problem

A monitor writes at most one row per day into status_log(day, status), with day as a YYYY-MM-DD date and status either 'up' or 'down'. Some days have no row because the monitor was offline. Collapse the log into runs: a run is a stretch of consecutive calendar days that all have a row with the same status. Return status, start_day, end_day and days for every run, sorted by start_day. A missing day ends a run just like a change of status does.

Examples

Input:  status_log = [("2026-09-01", "up"), ("2026-09-02", "up"), ("2026-09-03", "down"), ("2026-09-04", "up"), ("2026-09-05", "up")]
Output: [("up", "2026-09-01", "2026-09-02", 2), ("down", "2026-09-03", "2026-09-03", 1), ("up", "2026-09-04", "2026-09-05", 2)]
Input:  status_log = [("2026-09-01", "up"), ("2026-09-02", "up"), ("2026-09-04", "up")]
Output: [("up", "2026-09-01", "2026-09-02", 2), ("up", "2026-09-04", "2026-09-04", 1)]
Why:    nothing was recorded on 09-03, so the up run breaks there
Input:  status_log = [("2026-09-30", "down")]
Output: [("down", "2026-09-30", "2026-09-30", 1)]
Why:    edge case, a single row is a run of one day

Hints

0 / 3

Stuck on the idea rather than the code? Window Functions covers it.