MySQL日记3: 各部门工资最高的员工
输入:
Employee 表:
+----+-------+--------+--------------+
| id | name | salary | departmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+
Department 表:
+----+-------+
| id | name |
+----+-------+
| 1 | IT |
| 2 | Sales |
+----+-------+
输出:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
| IT | Max | 90000 |
+------------+----------+--------+
解释:Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。
思路:
每个部门的最高薪资;
找到did一样、salary一样的人,把这些人的信息展示出来。
SELECT
d.name AS Department, e.name AS Employee, e.salary AS Salary
FROM
Employee e
JOIN
(SELECT departmentId, MAX(salary) AS maxsal FROM Employee GROUP BY departmentId) t
ON
e.salary = t.maxsal AND e.departmentId = t.departmentId
JOIN
Department d
ON
e.departmentId = d.id
;