zoukankan      html  css  js  c++  java
  • [LeetCode][SQL]Department Highest Salary

    Department Highest Salary

    The Employee table holds all employees. Every employee has an Id, a salary, and there is 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 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.

    +------------+----------+--------+
    | Department | Employee | Salary |
    +------------+----------+--------+
    | IT         | Max      | 90000  |
    | Sales      | Henry    | 80000  |
    +------------+----------+--------+

    https://leetcode.com/problems/department-highest-salary/


    一开始去找工资比所有人高的人,当雇员表只有一个人的时候结果就不对了。

    1 # wrong answer !!!
    2 select D.Name, E1.Name, E1.Salary from Employee E1, Employee E2, Department D 
    3 where E1.DepartmentId = E2.DepartmentId and E1.Salary >= E2.Salary
    4     and E1.DepartmentId = D.Id

    于是反过来找,先找出工资比任意一个人低的所有人组成子表,目标员工不在子表中。

    1 select D.Name, E.Name, E.Salary from Employee E, Department D  
    2 where E.DepartmentId = D.Id and
    3 E.Id not in
    4 (
    5     select E1.Id from Employee E1, Employee E2
    6     where E1.DepartmentId = E2.DepartmentId and E1.Salary < E2.Salary
    7 )
     
     
  • 相关阅读:
    学习进度条--第十四周
    第二次团队冲刺--9
    第二次团队冲刺--8
    课堂练习--最少花费的购买书籍
    第二次团队冲刺--7
    第二次团队冲刺--6
    第二次团队冲刺--5
    软工第四周进度表
    软工第四周过程总结
    个人作业之二柱子四则运算2升级版
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4594082.html
Copyright © 2011-2022 走看看