Aggregate Before Joining When the Grain Requires It
Aggregating one side before joining can align an input with the desired result grain and avoid repeated contributions.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a book report
If a book has two authors and three copies, joining both detailed lists creates six author-copy pairs. A count of copies computed first is three. Cardinality from frequencies explains why the combined detail rows multiply.
Retain the needed relationships
If a report genuinely needs every pair, the product is the desired output. State the grain of the result before aggregating to one row per book.[1]
Avoid multiplication across independent child lists
An order has two lines and three shipment events. Joining both child tables directly on order ID produces six combinations. Summing line amounts there repeats each line three times. Aggregate each child relation at order grain before combining summaries. See row granularity.
Lines: 4 and 6 → total 10
Events: 3 → event count 3
Expanded join sums line amounts to 30
Join the separate order-level summaries to retain 10 and 3
Decide how childless orders should appear
A grouped child query alone does not create a zero-child summary. A left join from orders can preserve the parent. Apply zero or missing defaults according to the meaning of the aggregate.