Department Top Three Salaries
HardLeetCodeSQL: Window Functions
Hint and exampleShowHide
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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | Concept | Easy | Read the answer to What is the difference between ROW_NUMBER, RANK and DENSE_RANK? | |||
| 2 | Rank Scores | LeetCode | Medium | Solve Rank Scores on LeetCode (opens in a new tab) | |||
| 3 | Consecutive Numbers | LeetCode | Medium | Solve Consecutive Numbers on LeetCode (opens in a new tab) | |||
| 4 | Last Person to Fit in the Bus | LeetCode | Medium | Solve Last Person to Fit in the Bus on LeetCode (opens in a new tab) | |||
| 5 | Restaurant Growth | LeetCode | Medium | Solve Restaurant Growth on LeetCode (opens in a new tab) | |||
| 6 | Department Top Three Salaries | LeetCode | Hard | Solve Department Top Three Salaries on LeetCode (opens in a new tab) |