// window reference

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.

Categoría
Ventana
Returns
integer streak id
In this category
20 of 79

Sintaxis

ROW_NUMBER() OVER (ORDER BY d) - ROW_NUMBER() OVER (PARTITION BY state ORDER BY d) AS streak_id

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí MySQL 8.0+
SQLite Sí SQLite 3.25+
Oracle Sí Supported under this name.

Ejemplos

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;

Conviene saberlo

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.