Joins with aggregates

Stage 4: Joins · Lesson 17 of 17 · 6 min read · free, interactive

Joins and GROUP BY work together: join first to bring the columns you need side by side, then group.

SELECT p.name, COUNT(*) AS purchases, SUM(pu.qty) AS units
FROM purchases pu
JOIN players p ON p.id = pu.player_id
GROUP BY p.id, p.name;

With a LEFT JOIN, players without purchases still get a row — but be careful what you count. COUNT(*) counts that NULL-filled row as 1; COUNT(pu.id) correctly gives 0:

SELECT p.name, COUNT(*) AS wrong, COUNT(pu.id) AS right
FROM players p
LEFT JOIN purchases pu ON pu.player_id = p.id
GROUP BY p.id, p.name;

Tip: Group by the id as well as the name: two different players could share a name.

Practice

Each answer runs in your browser and is checked on hidden data.

Previous: Joining a table to itself · All lessons