185. Department Top Three Salaries
- Total Accepted: 8926
- Total Submissions: 57724
- Difficulty: Hard
- Contributors: Admin
The Employee
table holds all employees. Every employee has an Id, and there is also a column for the department Id.
+----+-------+--------+--------------+ | Id | Name | Salary | DepartmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | | 5 | Janet | 69000 | 1 | | 6 | Randy | 85000 | 1 | +----+-------+--------+--------------+
The Department
table holds all departments of the company.
+----+----------+ | Id | Name | +----+----------+ | 1 | IT | | 2 | Sales | +----+----------+
Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows.
+------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | IT | Randy | 85000 | | IT | Joe | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+
Code
# Write your MySQL query statement below select d1.Name as Department, e1.Name as Employee, e1.Salary as Salary from Employee e1 join Department d1 on d1.Id = e1.DepartmentId where 3 > (select count(distinct e2.Salary) from Employee e2 where e2.DepartmentId = e1.DepartmentId and e2.Salary > e1.Salary)
Idea
line 2~5 is just joining two tables, Employee
and Department
. line 6-9 makes sure the selection includes employees who earns top three.
Reference: https://discuss.leetcode.com/topic/8562/accepted-solution-without-group-by-or-order-by