按国家划分的月度收入,仅限活跃客户
使用 HAVING 方式过滤客户的财务报表
查看输入和输出预览
输入
- 查询应返回什么?
- Monthly revenue per country for 2025, counting only customers who placed more than 3 orders in 2025. Sort by month, then revenue descending.
- 表和列(可选)
- orders(id, customer_id, total_cents integer, created_at timestamp) customers(id, country text, signup_at timestamp)
- SQL 方言
- PostgreSQL
- 查询风格
- 可读(CTE,每行一个子句)
- 说明
- 简要
输出(节选)
```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;
```
**使用给定的模式。**
CTE 找出 2025 年订单超过三笔的客户;主查询仅保留这些客户的订单,将每笔订单截取到月份并按月度和国家汇总收入。日期范围为左闭右开,因此 12 月 31 日只计入一次…