Practice · Agriculture · Hard
For each crop, number its rows from the most recent year (rn = 1) to oldest, using a partitioned window. Return crop, year, million_tonnes and rn, ordered by crop then rn.
Runs in your browser. No signup needed.
ROW_NUMBER() OVER (PARTITION BY crop ORDER BY year DESC). PARTITION BY restarts the numbering per crop.
SELECT crop, year, million_tonnes,
ROW_NUMBER() OVER (PARTITION BY crop ORDER BY year DESC) AS rn
FROM crops
ORDER BY crop, rn;
The reference solution is checked automatically when you run your query on the practice page — results are compared row by row, and order matters for this one.
PARTITION BY is “GROUP BY that keeps the rows” — you get a number per group without collapsing the detail. (SQLite docs)