SQL CUME_DIST function
Returns the number of partition rows with a value less than or equal to the current row, divided by the total rows in the partition, a value in (0, 1].
- Catégorie
- Fenêtre
- Returns
double precision / float- In this category
- 10 of 79
Syntaxe
CUME_DIST() OVER (PARTITION BY g ORDER BY x)
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
SELECT product, price,
CUME_DIST() OVER (ORDER BY price) AS price_dist
FROM products;
Any engine
-- rows in the most expensive quartile WITH d AS ( SELECT p.*, CUME_DIST() OVER (ORDER BY price DESC) AS cd FROM products p ) SELECT * FROM d WHERE cd <= 0.25;
Bon à savoir
- CUME_DIST counts ties in: all peers get the same value, equal to the fraction of rows up to and including the last peer. PERCENT_RANK gives peers the rank of the first one instead.
- The maximum value is always exactly 1; the minimum is greater than 0 (it is at least peers / total rows).
- Without ORDER BY every row is a peer of every other row, so CUME_DIST returns 1 everywhere.
Questions about CUME_DIST
How is CUME_DIST different from PERCENT_RANK?
CUME_DIST = rows at or below (including peers and the current row) / total rows, so it never returns 0 and hits exactly 1 at the top. PERCENT_RANK = (rank - 1) / (rows - 1), which starts at 0. With ties, CUME_DIST gives every peer the value through the last peer.
Can CUME_DIST be used for percentiles?
Yes. CUME_DIST() OVER (ORDER BY x) <= 0.25 keeps the lowest quartile without splitting a tie group, and the smallest x with CUME_DIST >= 0.25 is exactly PERCENTILE_DISC(0.25). That works on MySQL and SQLite, which lack PERCENTILE_DISC.
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.