Top-N per Group & Window Patterns
Pattern 1: Top-N per group
Rank inside each group, then filter:
WITH ranked AS (
SELECT *, row_number() OVER (PARTITION BY group_col ORDER BY value DESC) AS rn
FROM t
)
SELECT * FROM ranked WHERE rn <= N;
- Use
rank()/dense_rank()instead of row_number if ties should all be included - Alternatives:
DISTINCT ON(N = 1 only, PostgreSQL),LATERAL … LIMIT N
Pattern 2: First/last row per entity
row_number() … ORDER BY created_at ASC → first; DESC → latest
Or DISTINCT ON (user_id) … ORDER BY user_id, created_at DESC
Pattern 3: Deduplicate rows ⭐
Keep one row per duplicate group and delete the rest:
DELETE FROM t WHERE id IN (
SELECT id FROM (
SELECT id, row_number() OVER (PARTITION BY dup_columns ORDER BY id) AS rn FROM t
) x WHERE rn > 1
);
Pattern 4: Percent of total & contribution
100.0 * value / sum(value) OVER (PARTITION BY group)
Pattern 5: Compare with the group
- Difference from the group average:
amount - avg(amount) OVER (PARTITION BY user_id) - Is this the group's maximum?
amount = max(amount) OVER (PARTITION BY …)
Pattern 6: Cumulative distribution / Pareto (80/20)
Which few categories make up 80% of spending? Running share: sum(total) OVER (ORDER BY total DESC) / sum(total) OVER ()
Performance tips
- An index matching
(PARTITION BY cols, ORDER BY cols)can avoid a sort - Several window functions with the same OVER clause share one sort — use a named
WINDOW - Filter as much as possible in WHERE before the window functions run
Example
-- 1. Top 2 categories per city (by total spent)
WITH city_cat AS (
SELECT COALESCE(u.city, 'Unknown') AS city, c.name AS category, sum(e.amount) AS total
FROM expenses e
JOIN users u ON u.id = e.user_id
JOIN categories c ON c.id = e.category_id
GROUP BY 1, 2
),
ranked AS (
SELECT *, dense_rank() OVER (PARTITION BY city ORDER BY total DESC) AS rnk
FROM city_cat
)
SELECT city, rnk, category, total FROM ranked WHERE rnk <= 2 ORDER BY city, rnk;
-- 2. Each user's first-ever expense
SELECT user_id, title, spent_on FROM (
SELECT *, row_number() OVER (PARTITION BY user_id ORDER BY spent_on, id) AS rn FROM expenses
) t WHERE rn = 1;
-- 3. Remove duplicates (create some first)
INSERT INTO expenses (user_id, category_id, title, amount, spent_on)
SELECT user_id, category_id, title, amount, spent_on FROM expenses WHERE id IN (1, 2);
SELECT title, count(*) FROM expenses GROUP BY user_id, title, amount, spent_on HAVING count(*) > 1;
DELETE FROM expenses WHERE id IN (
SELECT id FROM (
SELECT id, row_number() OVER (PARTITION BY user_id, title, amount, spent_on ORDER BY id) AS rn
FROM expenses
) d WHERE rn > 1
); -- DELETE 2
SELECT count(*) FROM expenses; -- back to 31
-- 6. Pareto: categories making up ~80% of spending
WITH cat AS (
SELECT c.name, sum(e.amount) AS total
FROM expenses e JOIN categories c ON c.id = e.category_id GROUP BY c.name
)
SELECT name, total,
round(100.0 * sum(total) OVER (ORDER BY total DESC) / sum(total) OVER (), 1) AS cumulative_pct
FROM cat
ORDER BY total DESC;