Department Top Three Salaries
Task: Find the employees who earn the top three unique salaries in each of the departments.
Table: Employee
+--------------+--------------+
| Column Name | Type |
+--------------+--------------+
| id | INT |
| name | varchar(255) |
| salary | INT |
| departmentId | INT |
+--------------+--------------+
Table: Department
+-------------+--------------+
| Column Name | Type |
+-------------+--------------+
| id | INT |
| name | varchar(255) |
+-------------+--------------+
Input: Employee table:
+----+-------+--------+--------------+
| id | name | salary | departmentId |
+----+-------+--------+--------------+
| 1 | Joe | 85000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
| 7 | Will | 70000 | 1 |
+----+-------+--------+--------------+
Department table:
+----+-------+
| id | name |
+----+-------+
| 1 | IT |
| 2 | Sales |
+----+-------+
Output:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Joe | 85000 |
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Will | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+ View Reference Solution & Explanation ▼
This solution uses a `JOIN` to combine data from multiple tables, window functions to perform calculations across a set of rows related to the current row, and a subquery as a derived table or inline value.
SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary FROM (SELECT departmentId, name, salary, DENSE_RANK() OVER(PARTITION BY departmentId ORDER BY salary DESC) as rank FROM Employee) e JOIN Department d ON e.departmentId = d.id WHERE e.rank <= 3;