Group and window phases
Overview
Use grouped aggregates and window functions together and identify which rows are visible to each phase. Grouping changes row granularity; window calculations retain the rows of their input relation.
First example
SELECT customer_id,SUM(amount) AS total,SUM(SUM(amount)) OVER () AS grand_total FROM lq_order WHERE status='paid' GROUP BY customer_id HAVING SUM(amount)>=200 ORDER BY customer_id;Observed SQLite result (rows in JSON):
[ [ 1, 250, 500 ], [ 2, 250, 500 ]]How it works
WHERE selects paid orders before grouping: three orders remain. Group by customer, then HAVING removes groups below a total of 200. Two groups survive with totals 250 each. SUM(SUM(amount)) OVER () operates over those groups and returns 500 for each. COUNT(*) OVER () would count groups, not underlying orders. Window results cannot be filtered in the same query block using WHERE or HAVING in PostgreSQL or SQLite; compute ROW_NUMBER in a CTE and filter in the outer query. In example two, rank paid orders by amount descending and id ascending within each customer: IDs 2 and 3 win. Window ORDER BY determines calculation order, not final output order. DISTINCT operates on projected values, so adding a row number may prevent duplicate removal. Avoid bare ungrouped columns even when SQLite accepts them.
Practical example
WITH ranked AS (SELECT id,customer_id,ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC,id) AS rn FROM lq_order WHERE status='paid') SELECT customer_id,id FROM ranked WHERE rn=1 ORDER BY customer_id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 3 ]]Practice and mistakes
Practice: raise the HAVING threshold to 251; predict no rows. Hint 1: HAVING precedes window calculations. Hint 2: compare COUNT() with SUM(COUNT()) OVER () at threshold 200. The latter is 3 for both groups.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE lq_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);CREATE TEMP TABLE lq_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES lq_customer(id), amount INTEGER NOT NULL CHECK(amount>=0), status TEXT NOT NULL CHECK(status IN ('paid','pending')));INSERT INTO lq_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');INSERT INTO lq_order VALUES(1,1,100,'paid'),(2,1,150,'paid'),(3,2,250,'paid'),(4,2,50,'pending'),(5,4,80,'pending'),(6,1,150,'pending');CREATE INDEX lq_order_amount ON lq_order(amount,id);CREATE INDEX lq_order_customer ON lq_order(customer_id);
SELECT customer_id,SUM(amount) AS total,SUM(SUM(amount)) OVER () AS grand_total FROM lq_order WHERE status='paid' GROUP BY customer_id HAVING SUM(amount)>=200 ORDER BY customer_id;ROLLBACK;Expected result, not executed: [[1, 250, 500], [2, 250, 500]]