// window reference

SQL PERCENT_RANK vs CUME_DIST

PERCENT_RANK positions a row by its rank over (rows - 1); CUME_DIST positions it by the share of rows at or below it, so ties land at the top of their group.

类别
窗口
Returns
double precision / float
In this category
14 of 79

语法

PERCENT_RANK() OVER (ORDER BY x) | CUME_DIST() OVER (ORDER BY x)

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 MySQL 8.0+
SQLite 是 SQLite 3.25+
Oracle 是 Supported under this name.

示例

Any engine

SELECT name, score,
       PERCENT_RANK() OVER (ORDER BY score) AS pr,
       CUME_DIST()   OVER (ORDER BY score) AS cd
FROM players;
-- scores 70, 80, 90, 90, 95:
-- pr = 0, 0.25, 0.5, 0.5, 1
-- cd = 0.2, 0.4, 0.8, 0.8, 1

值得了解

  • Edge behaviour differs: PERCENT_RANK is 0 on the first row, 1 only on the last; CUME_DIST is never 0 and is exactly 1 for every row of the last tie group.
  • With duplicate ORDER BY values, PERCENT_RANK gives all peers the value of the first peer's position, CUME_DIST the value through the last peer. For scores 70, 80, 90, 90, 95 the two 90s get 0.5 and 0.8.
  • Both give tied rows identical values, so neither splits a tie group. They still put the cutoff in different places: pct <= 0.5 keeps both 90s under PERCENT_RANK and neither under CUME_DIST.

Questions about PERCENT_RANK vs CUME_DIST

Which should I use for a 'bottom N percent' filter?

CUME_DIST <= 0.25 keeps rows whose whole tie group fits inside the first 25% of rows, so the result never exceeds 25%. PERCENT_RANK <= 0.25 keeps rows whose first peer starts within the first 25% of positions, so a tie group straddling the line comes in whole and the result can exceed 25%. CUME_DIST matches how PERCENTILE_DISC picks its value.

Can both be 0 or 1 on the same row?

Never 0: the first row has PERCENT_RANK 0 but CUME_DIST of at least 1/N. Both can be 1: the last row has CUME_DIST 1, and PERCENT_RANK is also 1 there unless it ties with an earlier row.

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.