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 )
     
     
  • 相关阅读:
    Git(五):Git分支管理策略
    Git(四):Git远程操作详解
    Git(三):Git 使用规范流程
    Git(二):常用 Git 命令清单
    Git(一):Eclipse中配置Git
    (一)Spring’s MVC Architecture
    Maven(九)”编码 gbk 的不可映射字符“ 问题解决方案
    Maven(八) Maven项目和testng结合应用
    Maven(七) maven 常用命令
    Maven(四-2) Maven pom.xml 配置详解
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4594082.html
Copyright © 2011-2022 走看看