Percentile Discrete Median Per Group

Compute the exact median per group using the percentile_disc window function with a 0.5 fraction parameter.

SqlData Integrity

Code

sqlsnippet
6 lines
SELECT DISTINCT
  department,
  PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary)
    OVER (PARTITION BY department) AS median_salary
FROM employees
ORDER BY department;

How the snippet works

At its core this is a single SELECT statement against employees.

Concretely, the SQL combines: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the employees table.

Statements that matter

SELECT DISTINCT
  department,
  PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary)
    OVER (PARTITION BY department) AS median_salary
FROM employees
ORDER BY department;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`employees`.