IntermediateGROUP BY & Aggregation

Percentile: find median salary

The query

SQL
SELECT
  dept_id,
  PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary,
  PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY salary) AS p25_salary,
  PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY salary) AS p75_salary
FROM employees
GROUP BY dept_id
ORDER BY dept_id;
Tested against PostgreSQL 16

Note

PERCENTILE_CONT for continuous (interpolated) median. PERCENTILE_DISC for actual data value.

Tables referenced