Problem
The Employee
table holds all employees. Every employee has an Id, and there is also a column for the department Id.
1 |
|
The Department
table holds all departments of the company.
1 |
|
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 (order of rows does not matter).
1 |
|
Explanation:
In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.
Explanation
-
First
INNER JOIN
Employee table and Department table by the DepartmentId. -
Then in order to return the top 3 Salary in the same department, we notice that the number of Salary is greater than the top 3 salary is less than 3. For example, there are only 2 salary that is higher than the third highest salary person; there are only 1 salary that is higher than the second highest salary person; there are 0 salary that is higher than the first highest salary person. So, in the
WHERE
query, we put() < 3
. Inside the paranthesis, we return a subquery withSELECT count(DISTINCT Salary)
from the Salary table. Inside this subquery, we match the subquery’s DepartmentId and choose only subquery’s Salary greater than the maching Salary. -
Finally we return the selected column.
Solution
1 |
|