IntermediateGROUP BY & Aggregation

Salary distribution by band

The query

SQL
SELECT
  CASE
    WHEN salary < 30000 THEN 'Under 30k'
    WHEN salary < 50000 THEN '30k-50k'
    WHEN salary < 70000 THEN '50k-70k'
    WHEN salary < 100000 THEN '70k-100k'
    ELSE 'Over 100k'
  END AS salary_band,
  COUNT(*) AS employee_count,
  ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 1) AS percentage
FROM employees
WHERE salary IS NOT NULL
GROUP BY salary_band
ORDER BY MIN(salary);
Tested against PostgreSQL 16

Note

CASE-based bucketing with window function to compute percentage of total without subquery.

Tables referenced