Sub topic 6
Building a One-Pass Summary Report
This chapter assumes that you know basic SELECT, WHERE, and ORDER BY, and that you have used aggregates such as count, sum, and avg. It also assumes that you understand that SQL NULL means an unknown or missing value.
A summary report often needs several related measurements:
- The total number of orders
- The number of paid orders
- The revenue from paid orders
- The percentage of refunded orders
You could run a separate query for each measurement. A filtered aggregate lets one grouped query calculate them together.
Start with the grouping
Suppose orders has these columns:
id: the order identifierstatus: such aspaid,refunded, orpendingamount: the order valuecreated_at: the order timestamp
To make a monthly report, group rows by the month extracted from created_at:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;date_trunc('month', created_at) changes each timestamp to the first instant of its month. The GROUP BY 1 refers to the first expression in the SELECT list.
Each group now represents one month. You can give each aggregate its own condition with FILTER.
Add several filtered aggregates
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
round(
100.0 * count(*) FILTER (WHERE status = 'refunded')
/ count(*),
1
) AS refund_pct
FROM orders
GROUP BY 1
ORDER BY 1;The query groups the table by month, then sends different rows to different aggregates:
count(*)receives every row in the month.- The paid count receives only rows whose status is
paid. - The paid revenue sum receives only paid rows.
- The refunded count receives only refunded rows.
- The refund percentage divides refunded orders by all orders.
The 100.0 makes the calculation use decimal division. If both operands were integers, some SQL expressions could perform integer division and discard the fractional part.
Make empty filtered results explicit
A filtered count returns 0 when no row matches. A filtered sum returns NULL when no row matches.
For example, a month with no paid orders produces NULL for paid_revenue. That result can be useful because it distinguishes “no paid rows” from a real sum of zero. Reports often need a numeric zero instead, so use coalesce:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
coalesce(
sum(amount) FILTER (WHERE status = 'paid'),
0
) AS paid_revenue
FROM orders
GROUP BY 1
ORDER BY 1;coalesce(value, replacement) returns the first non-NULL argument. Here, it changes a missing paid revenue total into 0.
Call the report “one-pass” because one grouped statement calculates all these measures together. This is simpler than issuing separate queries and joining their results. The database planner still decides how to execute the statement, so inspect EXPLAIN when performance matters.
Filter the report without changing its meaning
A top-level WHERE removes rows before grouping. For example:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE created_at >= current_date - interval '12 months'
GROUP BY 1
ORDER BY 1;This report contains only the last twelve months. The filtered aggregate still counts refunded rows within each remaining month. Use WHERE for the overall input set and FILTER for conditions that apply to individual measurements.
Exercise
How would you add a pending_orders column to the monthly report?
Show answer
Add count(*) FILTER (WHERE status = 'pending') AS pending_orders to the SELECT list.