SQL consecutive streaks with window functions
Group consecutive equal states by differencing two ROW_NUMBERs: one over all rows, one over rows grouped by state. Equal differences form each streak.
- Catégorie
- Fenêtre
- Returns
integer streak id- In this category
- 20 of 79
Syntaxe
ROW_NUMBER() OVER (ORDER BY d) - ROW_NUMBER() OVER (PARTITION BY state ORDER BY d) AS streak_id
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Oui | Supported under this name. |
| PostgreSQL | Oui | Supported under this name. |
| MySQL | Oui | MySQL 8.0+ |
| SQLite | Oui | SQLite 3.25+ |
| Oracle | Oui | Supported under this name. |
Exemples
Any engine
-- longest winning streak per player
WITH g AS (
SELECT player, day, result,
ROW_NUMBER() OVER (PARTITION BY player ORDER BY day)
- ROW_NUMBER() OVER (PARTITION BY player, result ORDER BY day) AS streak
FROM matches
WHERE result IN ('win', 'loss')
)
SELECT player, MAX(cnt) AS longest_win_streak
FROM (
SELECT player, streak, COUNT(*) AS cnt FROM g
WHERE result = 'win'
GROUP BY player, streak
) s
GROUP BY player;
Bon à savoir
- Both ROW_NUMBERs must share the same row order and it must be deterministic; otherwise rows of one streak can interleave and split it.
- The difference trick only groups by equality of the partition key. For streaks with a condition (days with sales > 0), first derive a 0/1 flag column and partition on it.
- Current streak and longest streak are different queries: the current one is the streak containing the latest row; the longest is the largest COUNT(*) per streak id.
Questions about Consecutive Streaks
Why does ROW_NUMBER minus ROW_NUMBER find streaks?
Within a run of consecutive same-state rows, both numbers advance by exactly 1, so their difference is constant for the whole run and changes when the state flips. It needs no lag comparison and no recursive CTE.
How do I get the current streak, not the longest?
Find the latest streak id (the one containing MAX(day)), then COUNT its rows; or in a single pass, COUNT(*) OVER (PARTITION BY player, streak_id) and pick the row at MAX(day).
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.