Grouping Rows by One Column

Grouping collects rows that share a key so an aggregate can describe each group's observations.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace three sales
  2. Account for output grain
  3. Calculate one result row per selected group
  4. Account for groups missing from input

Trace three sales

Rows north with values 4 and 5 and west with value 6 produce group sums north 9 and west 6. Grouping records with maps illustrates the state a similar in-memory process could keep.

Account for output grain

The result has one row per observed region under this query. A list of all regions needs separate reference data if zero-activity regions should appear. See row granularity.[1]

Calculate one result row per selected group

Suppose two readings from east have counts four and eight, and one from west has count five. Grouping by region yields east total twelve and west total five. A count or sum across all rows would instead yield one result. See grouping records with maps.

WITH readings(region, amount) AS (VALUES ('east',4), ('west',5), ('east',8))
SELECT region, SUM(amount) FROM readings GROUP BY region ORDER BY region;
-- Expected rows: east 12, west 5.

Account for groups missing from input

An expected region with no source row does not appear just because other regions were grouped. Start from a reference list when a report must display empty groups. Test that case explicitly.

References

  1. PostgreSQL Global Development Group, Queries ↩