File size: 752 Bytes
7814c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
-- Template: Customer Order Aggregation
-- Pattern: Aggregate metrics by customer dimension
-- Use Case: Calculate total order value, count, average per customer

SELECT 
    c.customer_id,
    c.name,
    c.email,
    COUNT(o.order_id) as total_orders,
    SUM(o.total_amount) as total_spent,
    AVG(o.total_amount) as avg_order_value,
    MIN(o.order_date) as first_order_date,
    MAX(o.order_date) as last_order_date
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name, c.email
ORDER BY total_spent DESC;

-- Key Concepts:
-- - LEFT JOIN to include customers with no orders
-- - Multiple aggregations (COUNT, SUM, AVG, MIN, MAX)
-- - GROUP BY all non-aggregated columns
-- - ORDER BY to rank results