1. Problem 1 — Customers With No Orders

SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

2. Problem 2 — Top 5 Customers by Spend

Order of SQL

SELECT c.id, c.name, SUM(o.total_cents) AS total_spent
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.status <> 'cancelled'
GROUP BY c.id, c.name
ORDER BY total_spent DESC
LIMIT 5;

3. Problem 3 — Orders Above Their Customer's Average

SELECT id, customer_id, total_cents
FROM (
    SELECT id, customer_id, total_cents,
           AVG(total_cents) OVER (PARTITION BY customer_id) AS customer_avg
    FROM orders
) t
WHERE total_cents > customer_avg;

4. Problem 4 — Running Total Per Customer_id

SELECT id, placed_at, total_cents,
       SUM(total_cents) OVER (
           PARTITION BY customer_id
           ORDER BY placed_at
           ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM orders
ORDER BY customer_id, placed_at;
id total_cents running_total
1 1000 1000
2 500 1500
3 2000 3500
4 1200 4700

5. Problem 5 — Second Highest Order Per Customer

SELECT customer_id, id, total_cents
FROM (
    SELECT customer_id, id, total_cents,
           DENSE_RANK() OVER (PARTITION BY customer_id
                              ORDER BY total_cents DESC) AS rnk
    FROM orders
) t
WHERE rnk = 2;

6. Problem 6 — Monthly Revenue With Gaps Filled

SELECT g.month,
       COALESCE(SUM(o.total_cents), 0) AS revenue
FROM generate_series(
        '2026-01-01'::timestamptz,
        '2026-12-01'::timestamptz,
        interval '1 month'
     ) AS g(month)
LEFT JOIN orders o
       ON o.placed_at >= g.month
      AND o.placed_at <  g.month + interval '1 month'
      AND o.status <> 'cancelled'
GROUP BY g.month
ORDER BY g.month;