Adding Group Information Without Collapsing Rows

A window function can compute a value across related rows while retaining each detail row in its result.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a regional total
  2. Keep the next calculation at the right grain
  3. Attach a group summary to every qualifying detail row
  4. Inspect how pre-window filters change the result

Trace a regional total

For two north rows with amounts 3 and 4, a partition sum can show 7 on both source rows. Group aggregation instead produces one row for north with 7. See one-column grouping.

Keep the next calculation at the right grain

Summing the repeated window total would count the group more than once. Determine whether consumers need detail rows or a summary first. Row granularity gives that distinction.[1]

Attach a group summary to every qualifying detail row

Two readings in group north have values three and seven. A window sum partitioned by group can append total ten to both rows, retaining their IDs. Grouping with a plain aggregate returns one north row. See grouping by one column.

WITH reads(id, region, value) AS (VALUES (1,'north',3),(2,'north',7),(3,'west',5))
SELECT id, value, SUM(value) OVER (PARTITION BY region) AS region_total FROM reads ORDER BY id;
-- Expected: (1,3,10), (2,7,10), (3,5,5).

Inspect how pre-window filters change the result

A WHERE predicate can remove detail rows before window aggregates see them. If a display filter should leave a group total based on full original data, use a suitable outer query. Test a group of two and a singleton.

References

  1. PostgreSQL Global Development Group, Window Functions Tutorial ↩