Grand Totals Via Empty OVER Frame

Add grand totals next to detail rows with an empty OVER () window: aggregates without partition or order cover the whole result set.

SqlData Integrity

Code

snippet
-- empty frame:空 OVER () 不分组不排序,聚合覆盖整个结果集
-- 明细与总计放在同一条查询里,无需两次查询再拼接
WITH spend AS (
  SELECT * FROM (VALUES
    ('orders',  420),
    ('billing', 180),
    ('auth',     60)
  ) AS t(team, cents)
)
SELECT
  team,
  cents,
  SUM(cents) OVER () AS grand_total,
  ROUND(100.0 * cents / SUM(cents) OVER (), 1) AS share_pct
FROM spend
ORDER BY cents DESC;

How it works

At its core this is a single SELECT statement against spend.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; SUM aggregation; 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

The spend table is the working surface here.

Core lines

WITH spend AS (
  SELECT * FROM (VALUES
    ('orders',  420),
    ('billing', 180),
    ('auth',     60)
  ) AS t(team, cents)
)
SELECT
  team,
  cents,
  SUM(cents) OVER () AS grand_total,
  ROUND(100.0 * cents / SUM(cents) OVER (), 1) AS share_pct
FROM spend
ORDER BY cents DESC;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`spend`.