Skip to content
GreenSnippets

Percent of total with a window function

Show each row's share of the grand total or of its group without a self-join.

SQL
SELECT
  region,
  product,
  revenue,
  ROUND(100.0 * revenue / SUM(revenue) OVER (), 1)                      AS pct_of_total,
  ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY region), 1)   AS pct_of_region
FROM sales
ORDER BY region, revenue DESC;

Example / expected output

Output
-- region  product  revenue  pct_of_total  pct_of_region
-- EU      A           600        30.0           60.0

How it works

SUM(...) OVER () computes the total across all rows while still returning every row. Add PARTITION BY for a share within a group. Cast to numeric before dividing so integer division does not round everything to zero.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.