Memra

Aggregating across joins

◈ 2 cards

Join, then group — the reporting workhorse.

Join then summarize

The most common real query joins tables and then groups. Revenue per order = sum of quantity × unit_price over its line items:

SELECT o.id, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id
ORDER BY o.id;

The join builds the wide row set; GROUP BY collapses it back down per order.

orderbookqty × unit_priceline1The Glass Forest1 × 14.9914.991Northern Light2 × 9.9919.981SUM per order34.97GROUP BY o.id collapses the join back down.
The join widens the data to one row per line item; the GROUP BY narrows it back to one row per order. Aggregate after the join, never before it.
NORMAL ~/memra/learn/postgresql/aggregating-joins utf-8 LF