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 to the company.
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT | |
2 | Sales |
+----+----------+
Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales depart ment.
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
First of the cases not considered:
Select Department.name as department,employee.name as Employee, Max (employee.salary) as Salary from employee join DEPARTME NT on Employee.departmentid=department.id GROUP by Employee.departmentid;
(This situation can only show that the department has only one highest pay situation, if there is more than one salary at the same time to achieve the highest, only show a)
Positive solution:
SELECT Dep. Name as Department, EMP. Name as Employee, EMP. Salary
from Department DEP, Employee EMP
where EMP. Departmentid=dep. Id and
Emp. salary= (Select Max (Salary) from Employee E2 where E2. Departmentid=dep. ID)