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.
Code
-- 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
WHEREruns 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
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.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.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
- What relations does the SQL touch?
- `spend`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.