The Employee table holds all employees. Every employee has an ID, a salary, and there are 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 |+----+-------+--------+--------------+
The Department table holds all departments of the company.
+----+----------+| Id | Name |+----+----------+| 1 | IT | | 2 | Sales |+----+----------+
Write a SQL query to find employees who has the highest salary in each of the departments. For the above tables, Max have the highest salary in the IT department and Henry have the highest salary in the Sales depart ment.
+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 | | Sales | Henry | 80000 |+------------+----------+--------+
Select P.department as department, E2.name as Employee, p.salary from ( select D.name as department, D.id as Depar Tmentid, Max (e1.salary) as salary from Employee E1, Department d where E1.departmentid = D.id GROUP by D. Name, d.id) as P, Employee e2 where E2.departmentid = P.departmentid and e2.salary = p.salary;
Leetcode Department Highest Salary