Monthly revenue per country, active customers only
A finance report with a HAVING-style customer filter
See input + output preview
Input
- What should the query return?
- Monthly revenue per country for 2025, counting only customers who placed more than 3 orders in 2025. Sort by month, then revenue descending.
- Tables and columns (optional)
- orders(id, customer_id, total_cents integer, created_at timestamp) customers(id, country text, signup_at timestamp)
- SQL dialect
- PostgreSQL
- Query style
- Readable (CTEs, one clause per line)
- Explanation
- Brief
Output (excerpt)
```sql
WITH active_customers AS (
SELECT o.customer_id
FROM orders AS o
WHERE o.created_at >= DATE '2025-01-01'
AND o.created_at < DATE '2026-01-01'
GROUP BY o.customer_id
HAVING COUNT(*) > 3
)
SELECT
DATE_TRUNC('month', o.created_at)::date AS month,
c.country,
SUM(o.total_cents) / 100.0 AS revenue
FROM orders AS o
JOIN active_customers AS a ON a.customer_id = o.customer_id
JOIN customers AS c ON c.id = o.customer_id
WHERE o.created_at >= DATE '2025-01-01'
AND o.created_at < DATE '2026-01-01'
GROUP BY 1, 2
ORDER BY month, revenue DESC;
```
**Schema used as given.**
The CTE finds customers with more than three orders in 2025; the main query keeps only their orders, truncates each order to its month and sums revenue per month and country. The date range is half-open so 31 December is counted once…