Skip to content
Justice Tech School

Top N per Group

Use ROW_NUMBER in a subquery to get the best row per group.

Example
SELECT country, name, score FROM (
  SELECT country, name, score, ROW_NUMBER() OVER (PARTITION BY country ORDER BY score DESC) AS rn
  FROM students WHERE score IS NOT NULL
) WHERE rn = 1;

Result

country      | name    | score
Ghana        | Kofi    | 78
Kenya        | Wanjiru | 64
Nigeria      | Ada     | 92
South Africa | Sipho   | 59

Exercise

Number rows.

() OVER (ORDER BY a)

Quiz Test

What does PARTITION BY do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.