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.
- Write the query: For each player who bought something, return their
nameandspent— the total ofqty × priceover their purchases. Row order does not matter. - Find the bug: Return every player's
namewith their number of purchases aspurchases(0 if they never bought anything). Row order does not matter. - Fill in the blanks: Return every item's
namewith the total units sold asunits— 0 for items that never sold. Row order does not matter.
Previous: Joining a table to itself · All lessons