Ricavo mensile per paese, solo clienti attivi
Un report finanziario con filtro clienti in stile HAVING
Mostra anteprima di input e output
Input
- Cosa dovrebbe restituire la query?
- Monthly revenue per country for 2025, counting only customers who placed more than 3 orders in 2025. Sort by month, then revenue descending.
- Tabelle e colonne (opzionale)
- orders(id, customer_id, total_cents integer, created_at timestamp) customers(id, country text, signup_at timestamp)
- Dialetto SQL
- PostgreSQL
- Stile della query
- Leggibile (CTE, una clausola per riga)
- Spiegazione
- Breve
Output (estratto)
```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 usato così com'è.**
Il CTE individua i clienti con più di tre ordini nel 2025; la query principale conserva solo i loro ordini, tronca ogni ordine al mese e somma il ricavo per mese e paese. L'intervallo di date è semi-aperto, quindi il 31 dicembre viene contato una sola volta…