• 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

  • 相关阅读:
    memory consistency
    网页基础
    ECC
    RSA
    argparse模块
    009-MySQL循环while、repeat、loop使用
    001-mac搭建Python开发环境、Anaconda、zsh兼容
    013-在 Shell 脚本中调用另一个 Shell 脚本的三种方式
    012-Shell 提示确认(Y / N,YES / NO)
    014-docker-终端获取 docker 容器(container)的 ip 地址
  • 原文地址:https://www.cnblogs.com/lshao/p/9585537.html
Copyright © 2020-2023  润新知