Topic:
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 |+------------+----------+--------+
Test instructions: Employees who find the maximum wage for each department
Idea: First of all, it is clear that the maximum wage is the only, but the maximum wage staff is not necessarily the only, therefore, to first within the connection to find the maximum salary for each department, in order to follow the convenience, direct select out the corresponding ID and name, so only in and employee do once within the connection can be.
Sql:
SELECTT.name, e.name, E.salary fromEmployee E, (SELECTE.departmentid asId, D.name,MAX(e.salary) asmaxsalary fromEmployee E, Department DWHEREE.departmentid=d.idGROUP byd.id) TWHEREE.salary=T.maxsalary andE.departmentid=T.id;
PS: A few days ago Leetcode OJ problem, always internal Error t.t
[Leetcode-database] Department Highest Salary