SQL重要题型总结

类型一:按照某个组分类计算该组最高/最低的记录

  1. Department Highest Salary
184

解法一

​ 直接计算每个组的最高/最低记录

​ 使用IN做匹配

select 
    d.Name AS 'Department',
    e.Name AS 'Employee',
    e.Salary
from 
    Employee e inner join Department d
    on e.DepartmentId = d.Id
where 
    (e.Salary, e.DepartmentId) IN
    (select 
        max(Salary), DepartmentId
    From 
        Employee e2
    group by DepartmentId )

解法二

​ 使用ALL()函数

​ 需要将e和e2连接起来,限制于同一个部门进行比较

​ 不需要group by

select 
    d.Name AS 'Department',
    e.Name AS 'Employee',
    e.Salary
from 
    Employee e inner join Department d
    on e.DepartmentId = d.Id
where 
    e.Salary >= ALL(
    select 
        Salary
    from 
        Employee e2
    where 
        e.DepartmentId = e2.DepartmentId
    )

类型二:按照某个组分类计算该组最高/最低的前三名记录

解法一

​ 利用两个employee表连接, count(e2.Salary) < 3

select 
    de.Name AS 'Department',
    e.Name AS 'Employee',
    e.Salary
From
    Employee e 
    inner join 
    Department de
    on e.DepartmentId = de.Id
where 
     (select 
        count(distinct e2.Salary) 
     from 
        Employee e2
     where 
        e.Salary < e2.Salary 
        and e.DepartmentId = e2.DepartmentId) <= 3 # 前3个, 
;

解法二

​ 利用Dense_Rank建立一张有排序的表

​ 再利用排序筛选

select Department, Employee, Salary from
(select 
    de.Name AS Department, 
    e.Name AS Employee, 
    e.Salary
    DENSE_RANK() over(partition by de.Name order by e.Salary Desc) AS Rank
from 
    Employee e inner join Department de
    on e.DepartmentId = de.Id) a
where Rank <= 3

SQLZOO

https://sqlzoo.net/wiki/Nested_SELECT_Quiz

  1. Select the code that shows the countries belonging to regions with all populations over 50000
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 了解SQL 1.1 数据库基础 ​ 学习到目前这个阶段,我们就需要以某种方式与数据库打交道。在深入学习MyS...
    锋享前端阅读 1,159评论 0 1
  • mysql数据库中 :database : 文件夹table : 数据表(数据文件) 进入mysqlmysql -...
    赋闲阅读 585评论 0 0
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,803评论 18 399
  • 前天完成了晨读复盘,下午把工作总结做了,今晚再搞定行动复盘,突然很享受这个过程,觉得最近过的好充实,每天都能...
    叶思希阅读 227评论 0 3
  • 五一假期,刘若英《后来的我们》刷遍了我的朋友圈,有人怀念过往的那个人,有人表白现在陪在身边看电影的那个人,...
    澄清清的石灰水阅读 366评论 0 2