Lesson 30 of 30 · Advanced Queries
Final Boss: SQL Rankings Report with a CTE and Window Functions
The Oracle of Rankings blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
At the top of the Archive Vaults sits the Oracle of Rankings, who sees every hero's worth at a glance and answers only those who can do the same. She demands a single report: the champion of every class, measured against the whole realm. Build it as a view she can consult forever, and the Vaults are yours.
Battle plan
This final fight combines the chapter: a CTE that names a step, window functions with and without PARTITION BY, and a filter on window results in an outer query.
Views. A view is a query saved in the database under a name:
CREATE VIEW rich_heroes AS
SELECT name, gold FROM heroes WHERE gold > 500;
SELECT * FROM rich_heroes ORDER BY gold DESC;
After CREATE VIEW, rich_heroes behaves like a read-only table that always shows the current data. A view's query may start with WITH, so a CTE fits inside one.
Filter window results one level up. WHERE runs before window functions, so compute them in a CTE and filter in the query that reads it:
WITH numbered AS (
SELECT name, level,
ROW_NUMBER() OVER (ORDER BY level DESC) AS pos
FROM heroes
)
SELECT name, level FROM numbered WHERE pos <= 3;
Mind the order of operations: a window function only sees the rows that reach it. Filter too early and every rank and total is computed over fewer heroes.
heroes has the columns id, name, class, level, gold, guild_id and joined: 15 heroes in 5 classes, and no two of them have the same gold.
Assignment
-
Create a view named
oracle_reportwith exactly these columns, in this order, and one row per class:Column Meaning classthe class championthe name of the class's richest hero goldthe champion's gold realm_rankthe champion's rank by gold among all 15 heroes (richest = 1), using RANK()class_goldthe total gold of all heroes in that class Use a CTE inside the view.
-
End your code with a query that shows the whole report, sorted by
realm_rank(best first).
Eight tests guard the Oracle's sanctum. Pass them all to claim the Archive Vaults.
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 .