Leetcode ---部门最高薪水

时间:2018-08-08 00:17:44

标签: mysql

我正在尝试解决以下问题: 雇员表保存所有雇员。每个员工都有一个ID,一个薪水,并且还有一个部门ID列。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
+----+-------+--------+--------------+

“部门”表包含公司的所有部门。

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

编写一个SQL查询以查找每个部门中薪水最高的员工。对于上表,Max在IT部门中的薪水最高,而Henry在销售部门中的薪水最高。 但是我想知道为什么下面的mysql查询不能得到正确的结果。

    SELECT d.Name as Department, e.Name as Employee, e.Salary FROM Employee e
    left join Department d on e.DepartmentId=d.Id
    GROUP BY d.Name
    order by e.Salary desc limit 1

2 个答案:

答案 0 :(得分:1)

此查询将执行您想要的操作:

SELECT d.Name AS Department, e.Name AS Employee, e.Salary
FROM Department d
JOIN Employee e
ON e.DepartmentID = d.Id AND 
   e.Salary = (SELECT MAX(Salary) 
               FROM Employee e2
               WHERE e2.DepartmentId = d.Id);

它将部门表与该部门中薪水最高的该部门的雇员相连。

输出:

Department  Employee    Salary
Sales       Henry       80000
IT          Max         90000

答案 1 :(得分:0)

尝试一下:

SET @curRank = 0;  

SELECT * FROM (

SELECT  @curRank := @curRank + 1 AS rank, salary, e.id, e.name, DepartmentId
FROM dept d
 JOIN emp e ON e.DepartmentId = d.Id 
 ORDER BY salary DESC 

) AS tbl 

GROUP BY  departmentID

这将起作用。