Part 07 / Topic 5 of 8
Aggregates as windows
Any aggregate takes an OVER. With an ORDER BY inside, sum becomes a running total — delivered revenue accumulating through the months:
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue,
sum(revenue) OVER (ORDER BY month) AS running_total
FROM monthly
ORDER BY month;
month | revenue | running_total
------------+---------+---------------
2025-01-01 | 2069.00 | 2069.00
2025-02-01 | 135.00 | 2204.00
2025-03-01 | 150.00 | 2354.00
2025-04-01 | 1709.00 | 4063.00
(4 rows)
(GROUP BY built the monthly numbers; the window then ran across those — the two compose naturally, aggregates first, windows after.) Without ORDER BY, the windowed aggregate is the whole partition's total on every row — which is the share-of-total pattern:
SELECT category_id, name, price,
round(100 * price / sum(price) OVER (PARTITION BY category_id), 1) AS pct_of_category
FROM products
WHERE category_id IN (2, 4)
ORDER BY category_id, price DESC;
category_id | name | price | pct_of_category
-------------+--------------------+---------+-----------------
2 | Postgres Deep Dive | 55.00 | 61.1
2 | SQL for Beginners | 35.00 | 38.9
4 | Laptop Pro 14 | 1200.00 | 55.8
4 | Laptop Air 13 | 950.00 | 44.2
(4 rows)
Count, avg, min, max — all the same way. The "percentage of all orders" that needed a scalar subquery in Stage 1? count(*) OVER () does it inline.
🧪 Quick quiz — answer from memory, then check.
- What turns
sum(x) OVER (...)from a constant total into a running total? - Write "this row's share of the grand total of amount".
Show the answers
- An ORDER BY inside the OVER — the default frame then accumulates up to the current row.
amount / sum(amount) OVER ()(times 100 for percent).
Exercise 5: Payment method share
What to do: Per payment method: amount collected and its percentage of all money collected — one query, no scalar subquery.
Sample output:
method | collected | pct_of_all
--------+-----------+------------
card | 2715.00 | 55.9
upi | 1996.00 | 41.1
cash | 150.00 | 3.1
(3 rows)
💡 Hint: a window over an aggregate: sum(sum(amount)) OVER () — the inner sum is the GROUP BY's, the outer one windows across the groups.
Show the solution to Exercise 5
-- Exercise 5: Payment method share
SELECT method,
sum(amount) AS collected,
round(100 * sum(amount) / sum(sum(amount)) OVER (), 1) AS pct_of_all
FROM payments
GROUP BY method
ORDER BY collected DESC;