국가별 월별 매출, 활성 고객만
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년에 주문이 3개 이상인 고객을 찾습니다; 메인 쿼리는 해당 고객의 주문만 유지하고, 각 주문을 월 단위로 절단한 뒤 월별 및 국가별 매출을 합산합니다. 날짜 범위는 반닫힌 구간이므로 12월 31일은 한 번만 계산됩니다…