Percentage of total
SUM(SUM(x)) OVER () is the grand total evaluated after the GROUP BY.
The task
You want each customer's revenue and what percent of all revenue that represents, in one grouped query.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT customer_id,
SUM(amount) AS total,
ROUND(100.0 * SUM(amount)
/ SUM(SUM(amount)) OVER (), 1) AS pct_of_grand_total
FROM orders
GROUP BY customer_id
ORDER BY total DESC;
Como funciona
Window functions run after GROUP BY, so SUM(SUM(amount)) OVER () sums the already-grouped customer totals across all rows, giving the grand total without a second scan. The outer SUM(amount) stays the per-customer value. Writing 100.0 rather than 100 forces decimal division. With an integer column, SQL Server, PostgreSQL and SQLite divide integers by truncating, so 100 * SUM(qty) / SUM(SUM(qty)) OVER () would drop the decimals.
Variations
Cross-join the grand total (no window functions)
SELECT customer_id,
SUM(amount) AS total,
ROUND(100.0 * SUM(amount) / t.grand, 1) AS pct_of_grand_total
FROM orders
CROSS JOIN (SELECT SUM(amount) AS grand FROM orders) t
GROUP BY customer_id, t.grand
ORDER BY total DESC;
Questions that come up
Why does my percentage come out as 0 or 100?
Integer division. On SQL Server, PostgreSQL and SQLite, an integer divided by an integer is truncated: 3 / 10 is 0, so SUM(x) / SUM(SUM(x)) OVER () * 100 is 0 for every row except one that holds the whole total. MySQL and Oracle return 0.3. Multiply by 100.0 first, or CAST one operand to a decimal type.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.