IntermediateCTEs & Recursive

CTE for top customer per quarter

The query

SQL
WITH quarterly_spend AS (
  SELECT
    c.cust_id,
    c.name,
    DATE_PART('quarter', o.order_date) AS quarter,
    DATE_PART('year', o.order_date) AS year,
    SUM(o.total) AS quarter_spend
  FROM customers c
  JOIN orders o ON c.cust_id = o.cust_id
  WHERE o.status = 'completed'
  GROUP BY c.cust_id, c.name, quarter, year
),
ranked AS (
  SELECT *,
    RANK() OVER (PARTITION BY year, quarter ORDER BY quarter_spend DESC) AS rnk
  FROM quarterly_spend
)
SELECT year::INT, quarter::INT, name, quarter_spend
FROM ranked
WHERE rnk = 1
ORDER BY year, quarter;
Tested against PostgreSQL 16

Note

Two CTEs chained: first aggregates, second ranks. Clean and readable for quarterly analysis.

Tables referenced