✏️ Explanatory Question

Department Top 3 Salaries — top 3 earners in each department

👁 6 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 26: Ranking & Top-N Puzzles

145

Department Top 3 Salaries — top 3 earners in each department

Level: Coding Round — A LeetCode HARD problem; the "per group" + "ties count as one rank" twist is the challenge.

The Puzzle: Find the employees who are among the top 3 highest earners in each department. A "top 3 salary" means there are no more than two distinct salaries higher than it — so ties at a salary level all count as the same rank.

Sample Data — employees

idnamesalarydept_id
1Rumman9000010
2Krushna9000010
3Swetha8000010
4Ritesh7000010
5Manjula6000010
6Elitam5000020

Expected Output

dept_idnamesalary
10Rumman90000
10Krushna90000
10Swetha80000
10Ritesh70000
20Elitam50000

Dept 10 top-3 distinct salaries are 90k, 80k, 70k. BOTH people at 90k qualify, and 70k is still 3rd → 4 employees make the cut. Manjula (60k) is 4th → excluded.

The critical choice — DENSE_RANK, not ROW_NUMBER: "Top 3 salaries" means the top 3 distinct salary values, so tied employees share a rank. DENSE_RANK() gives ties the same rank with no gaps (1,1,2,3...), which is exactly right. ROW_NUMBER would wrongly cut off one of the two 90k earners.

Solution — DENSE_RANK Window Function (MySQL 8.0+)

SELECT dept_id, name, salary
FROM (
    SELECT dept_id, name, salary,
           DENSE_RANK() OVER (
               PARTITION BY dept_id
               ORDER BY salary DESC
           ) AS drnk
    FROM employees
) t
WHERE drnk <= 3
ORDER BY dept_id, salary DESC;

Solution 2 — Correlated Subquery (older MySQL 5.7)

-- An employee is "top 3" if fewer than 3 DISTINCT higher salaries exist in the dept
SELECT e.dept_id, e.name, e.salary
FROM employees e
WHERE (
    SELECT COUNT(DISTINCT e2.salary)
    FROM employees e2
    WHERE e2.dept_id = e.dept_id
      AND e2.salary > e.salary
) < 3
ORDER BY e.dept_id, e.salary DESC;

Why COUNT(DISTINCT ...) is essential in Solution 2: Without DISTINCT, the two 90k earners would each count the other as a "higher-or-equal" row, corrupting the rank. Counting distinct higher salaries correctly treats tied salaries as one level — mirroring DENSE_RANK's behaviour.

Which Ranking Function for "Top N"?

RequirementFunction
Top 3 distinct salary levels (ties included)DENSE_RANK
Exactly 3 rows, break ties arbitrarilyROW_NUMBER
Competition ranking with gapsRANK

Interviewer follow-up: "The business now wants exactly 3 employees per department, no more, even when salaries tie." → Switch to ROW_NUMBER() with a deterministic tie-breaker: ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC, id) then WHERE rn <= 3. This caps it at exactly 3 by using id to break salary ties — a different business rule requiring a different function.