// window reference

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.

카테고리
창
Returns
type of the ORDER BY expression
In this category
11 of 79

구문

PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) | PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g)

엔진 지원

엔진Support메모
SQL Server 예 SQL Server 2012+; window form only: OVER (PARTITION BY ...) is mandatory
PostgreSQL 예 ordered-set aggregate only; OVER is rejected
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle 예 aggregate and analytic (OVER) forms

예시

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;

알아 두면 좋은 정보

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, 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.