Deviopath › PostgreSQL

Median Salary per Department

Hard · Aggregation

The median is the middle value of a sorted list (the average of the two middle values when the count is even). PostgreSQL computes it with an ordered-set aggregate: percentile_cont(0.5) WITHIN GROUP (ORDER BY salary). It returns double precision, so cast it to numeric before rounding.

For every department (including departments with no employees), return department (name), employees (how many employees it has) and median_salary: the median salary cast to numeric and rounded to 2 decimals, or NULL for an empty department. Ignore employees without a department.

Next: Score Histogram with Empty Buckets