SQL PERCENTILE_DISC function
Returns the ordered value at which the cumulative distribution first reaches the given fraction: a real value from the data, not an interpolation.
- Categoría
- Ventana
- Returns
type of the ORDER BY expression- In this category
- 11 of 79
Sintaxis
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) | PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | SQL Server 2012+; window form only: OVER (PARTITION BY ...) is mandatory |
| PostgreSQL | Sí | ordered-set aggregate only; OVER is rejected |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Sí | aggregate and analytic (OVER) forms |
Ejemplos
PostgreSQL
SELECT PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price) AS median FROM products;
SQL Server
SELECT DISTINCT region,
PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY price)
OVER (PARTITION BY region) AS median_price
FROM products;
Conviene saberlo
- Syntax is inverted from other functions: the fraction goes first and the column is declared inside WITHIN GROUP (ORDER BY ...). Getting this backwards is the most common syntax error.
- MySQL and SQLite have no PERCENTILE_DISC. The exact emulation is the first row, in ORDER BY order, whose CUME_DIST() is at least the fraction.
- The two server engines disagree on form: PostgreSQL rejects OVER ('OVER is not supported for ordered-set aggregate'), SQL Server rejects the plain aggregate ('must have an OVER clause'). Oracle accepts both, so a portable median query does not exist.
Questions about PERCENTILE_DISC
What is the difference between PERCENTILE_DISC and PERCENTILE_CONT?
DISC returns an actual row's value (the smallest value whose cumulative share reaches the fraction); CONT interpolates between the two surrounding values and can return a value that appears nowhere in the data. DISC works on any orderable type, including text and dates.
Does PERCENTILE_DISC work in MySQL or SQLite?
No. Compute CUME_DIST() OVER (PARTITION BY g ORDER BY x) in a CTE, then take MIN(x) per group among rows where the CUME_DIST is >= the fraction. That returns exactly what PERCENTILE_DISC would.
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, 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.