Mix window functions with GROUP BY
Windows run after GROUP BY; a CTE makes the order explicit and the query readable.
The task
You want regional revenue totals, each region's percent of all revenue, and a rank by size, all in one result.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH region_totals AS (
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON c.id = o.customer_id
GROUP BY c.region
)
SELECT region, total,
ROUND(100.0 * total / SUM(total) OVER (), 1) AS pct_of_all,
RANK() OVER (ORDER BY total DESC) AS rank_by_size
FROM region_totals
ORDER BY total DESC;
工作原理
The CTE does the grouping first and hands the window functions a small, already-aggregated row set. The windows then compute across those rows: SUM(total) OVER () is the grand total, RANK orders the regions. You can nest aggregates directly inside windows (SUM(SUM(x)) OVER ...) without a CTE, but the two-step version is easier to read and to debug.
Variations
Nested form without the CTE
SELECT c.region,
SUM(o.amount) AS total,
ROUND(100.0 * SUM(o.amount)
/ SUM(SUM(o.amount)) OVER (), 1) AS pct_of_all,
RANK() OVER (ORDER BY SUM(o.amount) DESC) AS rank_by_size
FROM orders o
JOIN customers c ON c.id = o.customer_id
GROUP BY c.region
ORDER BY total DESC;
Questions that come up
Why can't I write RANK() over a raw column next to GROUP BY?
Because window functions evaluate after grouping, and any column they reference must either be in the GROUP BY or wrapped in an aggregate. SUM(SUM(x)) OVER (...) is legal; RANK() OVER (ORDER BY x) where x is neither grouped nor aggregated is not.
Keep reading
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.