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).

SqlData Fetching

Code

snippet
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 WHERE runs too early.

Putting it to use

Run the statement against the sales table.

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`sales` — referenced directly, no join needed.