RANK Over Grouped Totals
Rank grouped totals in one pass because window functions are evaluated after GROUP BY and can order by aggregate expressions like SUM(revenue).
Code
WITH sales(region, month, revenue) AS (
VALUES
('emea', '2026-01', 1200),
('emea', '2026-02', 1500),
('apac', '2026-01', 900),
('apac', '2026-02', 1100),
('amer', '2026-01', 700)
)
SELECT
region,
SUM(revenue) AS region_total,
-- 窗口函数在 GROUP BY 之后求值:排序对象是聚合结果 SUM(revenue)
RANK() OVER (ORDER BY SUM(revenue) DESC) AS rank_by_total,
-- 嵌套聚合合法:SUM(SUM(x)) OVER () 对聚合结果再求总和
SUM(SUM(revenue)) OVER () AS grand_total
FROM sales
GROUP BY region
ORDER BY rank_by_total;How it works
At its core this is a single SELECT statement against sales.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- To filter on a window function’s result you need an outer query or CTE; the same-level
WHEREruns too early.
Putting it to use
Run the statement against the sales table.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `sales` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.