美文网首页
[LeetCode] 系里最高薪水 Department Hig

[LeetCode] 系里最高薪水 Department Hig

作者: 产品第一帅 | 来源:发表于2017-08-31 03:13 被阅读0次

    Employee表和Department表,让我们找系里面薪水最高的人

    The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

    Employee

    | The Department table holds all departments of the company.

    Department

    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 department.

    最终结果

    这道题让给了我们两张表,Employee表和Department表,让我们找系里面薪水最高的人的,实际上这题是Second Highest SalaryCombine Two Tables的结合题,我们既需要联合两表,又要找到最高薪水,那么我们首先让两个表内交起来,然后将结果表需要的列都标明,然后就是要找最高的薪水,我们用Max关键字来实现,参见代码如下:


    解法一:使用JOIN连接 ,WHERE条件限制薪资最高


    SELECT    d.Name   AS Department,  e1.Name AS Employee, eQ.Salary FROM Employee e1

    JOIN   Department  d ON e1.DepartmentId=d.Id  

     WHERE Salary  IN      (SELECT      MAX(Salary)         FROM       Employee e2    WHERE e1.DepartmentId=e2.DepartmentId )


    解法二:直接用Where将两表连起来,然后找最高薪水的方法和上面相同


    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e, Department d

    WHERE e.DepartmentId = d.Id AND e.Salary = (SELECT MAX(Salary) FROM Employee e2 WHERE e2.DepartmentId = d.Id);

    解法三:用了>=符号,实现的效果跟Max关键字相同


    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e, Department d

    WHERE e.DepartmentId = d.Id AND e.Salary >= ALL (SELECT Salary FROM Employee e2 WHERE e2.DepartmentId = d.Id);

    相关连接 184.Department Highest Salary

    相关文章

      网友评论

          本文标题:[LeetCode] 系里最高薪水 Department Hig

          本文链接:https://www.haomeiwen.com/subject/yjufjxtx.html