FILTER inside an aggregate in SQL
One pass over the table, several differently filtered counts.
SELECT
customer_id,
COUNT(*) AS orders_total,
COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'pending') AS pending,
SUM(total) FILTER (WHERE status = 'paid') AS paid_value
FROM orders
GROUP BY customer_id;
How it works
FILTER (WHERE ...)restricts the rows one aggregate sees.- The outer
WHEREwould drop the rows for every column at once. SUM(CASE WHEN ... THEN 1 END)is the older spelling of the same idea.
Keywords and builtins used here
ASBYCOUNTFROMGROUPSELECTSUMWHERE
The run, in numbers
- Lines
- 8
- Characters to type
- 239
- Tokens
- 57
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 36 seconds.
Step 3 of 7 in Expressions, step 18 of 24 in Analytics & reporting.