zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    你好,世界!
    zabbix监控系统(四)创建监控项
    zabbix监控系统(三)监控主机
    zabbix监控系统(二)登录并配置用户
    zabbix监控系统(一)zabbix安装
    python介绍
    Cohen-Sutherland裁剪算法
    eclipse安装openGL方法(完整版)
    java第一课:安装环境变量和用记事本实现Hello World
    实验二
  • 原文地址:https://www.cnblogs.com/lshao/p/9585537.html
Copyright © 2011-2022 走看看