Skip to content
We areTOP 1%

Department Top Three Salaries

HardLeetCodeSQL: Window Functions
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

Rank the rows inside each group with DENSE_RANK() OVER (PARTITION BY ... ORDER BY ... DESC) in a subquery, then keep the ranks up to the limit, so tied values share a place.

Example: results(team, player, score) — top 2 distinct scores per team

team | player | score
A    | Asha   | 90
A    | Ravi   | 85
A    | Meera  | 85
A    | Kiran  | 70
B    | Dev    | 60
SELECT team, player, score
FROM (
  SELECT team, player, score,
         DENSE_RANK() OVER (PARTITION BY team ORDER BY score DESC) AS r
  FROM results
) t
WHERE r <= 2;
-- A: Asha 90, Ravi 85, Meera 85;  B: Dev 60

More in SQL: Window Functions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account