TheEmployeetable 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 |
+----+-------+--------+--------------+
TheDepartmenttable 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 |
+------------+----------+--------+
Solution 1:using correlated subqueries and joins
SELECT D.Name AS Department, E1.Name AS Employee, E1.Salary AS Salary
FROM Department AS D
JOIN Employee AS E1 ON D.Id = E1.DepartmentId
WHERE 3 >
(
SELECT COUNT(DISTINCT E2.Salary)
FROM Employee AS E2
WHERE E2.Salary > E1.Salary
AND E2.DepartmentId = E1.DepartmentId
)
ORDER BY Department, Salary
;
Solution 2: only using joins
SELECT d.Name as Department, e.Name as employee, e.Salary
FROM Employee e
JOIN Department d ON e.DepartmentId = d.Id
WHERE (e.DepartmentId, e.Salary) IN
(SELECT e1.DepartmentId, e1.Salary
FROM Employee e1
LEFT JOIN Employee e2 ON e1.DepartmentId = e2.DepartmentId AND e1.Salary < e2.Salary
GROUP BY e1.DepartmentId, e1.Salary
HAVING count(distinct e2.Salary) < 3);
Solution 3: use group by
SELECT department.Name Department, e1.Name Employee, e1.Salary
FROM employee e1
JOIN department ON e1.DepartmentId = department.Id
LEFT JOIN employee e2 ON e1.DepartmentId = e2.DepartmentId AND e1.Salary < e2.Salary
GROUP BY e1.Id
HAVING count(distinct e2.Salary) < 3
ORDER BY department.Name, e1.Salary desc;