• SQL 分组内求最大N个或最小N个


    题目描述

       表 Employee

    +----+-------+--------+--------------+
    | Id | Name  | Salary | DepartmentId |
    +----+-------+--------+--------------+
    | 1  | Joe   | 70000  | 1            |
    | 2  | Henry | 80000  | 2            |
    | 3  | Sam   | 60000  | 2            |
    | 4  | Max   | 90000  | 1            |
    | 5  | Janet | 69000  | 1            |
    | 6  | Randy | 85000  | 1            |
    +----+-------+--------+--------------+

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

    要求每个部门员工中挣得所在部门前三的工资,由于有多人可能工资一样,故每个部门求出的人数可能大于3
    结果如下:
    +------------+----------+--------+
    | Department | Employee | Salary |
    +------------+----------+--------+
    | IT         | Max      | 90000  |
    | IT         | Randy    | 85000  |
    | IT         | Joe      | 70000  |
    | Sales      | Henry    | 80000  |
    | Sales      | Sam      | 60000  |
    +------------+----------+--------+

    SQL语句
    select a.Name as Department,b.Name as Employee,b.Salary from
    Department a 
    join
    (select * from Employee e1 where (select count(distinct Salary) from Employee e2 where e2.Salary>e1.Salary and e1.DepartmentId=e2.DepartmentId)<3) b
    on b.DepartmentId=a.Id
    order by a.Id,b.Salary desc;
    #查出每个部门中工资是前三水平的员工
    select
    * from Employee e1
    where
    (select count(distinct Salary) from Employee e2 where e2.Salary>e1.Salary and e1.DepartmentId=e2.DepartmentId)
    <3

  • 相关阅读:
    富文本的使用
    sql
    # 多线程:为啥无法避免并发修改异常?(假设有两个线程,线程A,线程B),怎么避免并发修改异常?
    File&&字节流
    IO-字符流
    第二周疑问点
    异常
    常用API-Object+String
    学习JavaSE过程中的疑问点(第一周)
    JavaOOP
  • 原文地址:https://www.cnblogs.com/lshao/p/9585537.html
Copyright © 2020-2023  润新知