A retention analyst wants the most consistent buyers: customers who placed at least one order in each of July, August and September 2026.
From store_orders, return customer_id, orders_in_quarter and total_spent (both counting only orders from 1 July to 30 September 2026) for customers active in all three months. Order by customer_id.
Sample data
Table: store_orders
20 row(s) · showing first 8
| order_idINT | customer_idINT | order_dateDATE | order_amountNUMERIC(10,2) |
|---|---|---|---|
| 1 | 1 | 2026-07-05 | 1200.00 |
| 2 | 1 | 2026-08-11 | 900.00 |
| 3 | 1 | 2026-09-14 | 1500.00 |
| 4 | 1 | 2026-09-30 | 600.00 |
| 5 | 2 | 2026-07-20 | 3000.00 |
| 6 | 2 | 2026-09-02 | 2500.00 |
| 7 | 2 | 2026-10-03 | 1800.00 |
| 8 | 3 | 2026-07-08 | 700.00 |
store_orders
- order_idINT
- customer_idINT
- order_dateDATE
- order_amountNUMERIC(10,2)
- Step 1: Restrict the rows to the quarter in `WHERE` first. Without it, customer 2 (July, September and October orders) would also count three distinct months.
- Step 2: `COUNT(DISTINCT DATE_TRUNC('month', order_date))` counts how many different months a customer ordered in.
- Step 3: Requiring that count to equal 3 in `HAVING` keeps customers active in every month; customer 6's June order is excluded by the date filter, so their totals cover Q3 only.
SELECT customer_id,
COUNT(*) AS orders_in_quarter,
SUM(order_amount) AS total_spent
FROM store_orders
WHERE order_date >= DATE '2026-07-01'
AND order_date < DATE '2026-10-01'
GROUP BY customer_id
HAVING COUNT(DISTINCT DATE_TRUNC('month', order_date)) = 3
ORDER BY customer_id;More GROUP BY questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program