AdvancedWindow Functions

Percent of total using window functions

The query

SQL
SELECT
  d.dept_name,
  SUM(e.salary) AS dept_salary,
  SUM(SUM(e.salary)) OVER () AS total_salary,
  ROUND(
    SUM(e.salary) * 100.0 / SUM(SUM(e.salary)) OVER (), 2
  ) AS pct_of_total
FROM employees e
JOIN departments d ON e.dept_id = d.dept_id
GROUP BY d.dept_id, d.dept_name
ORDER BY dept_salary DESC;
Tested against PostgreSQL 16

Note

SUM(SUM(...)) OVER () — nested aggregation using window function over grouped result.

Tables referenced