Lesson 12 of 30 · Aggregates & Grouping
Boss: SQL GROUP BY Report with SUM, AVG and HAVING
The Tax Collector blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Every autumn the Tax Collector rides into the Archive Vaults with an iron ledger and a very long quill. He doesn't tax heroes one by one — he taxes whole classes, and he wants a flawless report on his desk before sundown. One wrong number and he doubles everyone's taxes.
Battle plan
This fight uses everything from Chapter 2: COUNT, SUM, AVG and ROUND, GROUP BY, and the difference between WHERE and HAVING. Remember the order in which a query runs:
FROM → WHERE (filter heroes) → GROUP BY (build the classes) → HAVING (filter classes) → SELECT → ORDER BY
The heroes table again — this time the columns that matter are class, level and gold:
| id | name | class | level | gold | guild_id | joined |
|---|---|---|---|---|---|---|
| 6 | Finn Oakheart | Warrior | 5 | 40 | 4 | 2025-06-01 |
| 8 | Hugo Stonebeard | Warrior | 23 | 1200 | 2 | 2024-05-09 |
| 11 | Kira Frostvale | Mage | 3 | 20 | NULL | 2025-07-15 |
| … | … | … | … | … | … | … |
One more tool for this fight: the Tax Collector only accepts whole coins. Dividing two whole numbers in SQLite drops the decimals, so SUM(gold) / 10 is exactly the tax he wants — for 1565 gold that's 156 coins, not 156.5.
Assignment
Write one query on heroes that produces the Tax Collector's report.
Rules:
- Heroes below level 5 are too young to pay taxes. Leave them out completely — they don't count anywhere in the report.
- Group the remaining heroes by
class. - Only classes whose remaining heroes own at least 1200 gold in total pay taxes. Leave out the other classes.
- Sort the classes by their total gold, richest first.
Columns, in this order:
classheroes— the number of taxpaying heroes in the classtotal_gold— their gold added upavg_gold— their average gold, rounded to 1 decimal placetax— one tenth of the total gold in whole coins, written asSUM(gold) / 10
Each passing test lands a hit on the Tax Collector. Make all eight pass to send him home with an empty ledger.
Premium lesson
Unlock the full Learn SQL course
- All 30 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The SQL cheat sheet has every topic of Learn SQL on one page.
Lesson last updated on .