当我们需要进行一些比较复杂的子查询时,聚合函数就会非常的麻烦,因此可以使用开窗函数进行分组再运用函数查询。窗口函数既可以显示聚集前的数据,也可以显示聚集后的数据,可以在同一行中返回基础行的列值和聚合后的结果列
常见运用场景: 对班里同学成绩进行排序
常见的窗口函数
开窗函数基本形式
func_name(<parameter>)
OVER(
[PARTITION BY <part_by_condition>]
[ORDER BY <order_by_list> ASC|DESC]
[rows between ?? And ??]
)
具体字段的解释看我的上一篇:SQL开窗函数之基本用法和聚合函数
percent_rank(): 按公式(rank-1)/(row-1)
进行计算
应用场景:不常用
cume_dist(): 获取组内小于等于当前rank值的行数/分组内总行数
应用场景:查询小于当前薪资的比例
select *,
rank() over(order by sales) as ranking,
percent_rank() over(order by sales) as percent_ranking,
cume_dist() over(order by sales) as cume
from Sales
头尾函数 first_value()
和 last_value()
主要用于获取分组字段内的第一个值或最后一个值,部分情况下相当于 max
或 min
应用场景: 查询部门最早发生销售记录日期和最近发生的销售记录日期
select *,
first_value(score) over(partition by cid),
first_value(score) over(partition by cid order by score),
last_value(score) over(partition by cid),
last_value(score) over(partition by cid order by score)
from sc;
NTILE()
函数用于将分区中的有序数据分为n个等级,记录等级数
NTILE(n)
OVER (
PARTITION BY <expression>[{,<expression>...}]
ORDER BY <expression> [ASC|DESC], [{,<expression>...}]
)
Ntile(n)
表示分成了n组
select *,
ntile(2) over(order by score desc) as 2_tile,
ntile(3) over(order by score desc) as 3_tile,
from sc;
select *,
ntile(2) over(partition by cid order by score desc) as 2_tile_group,
ntile(3) over(partition by cid order by score desc) as 3_tile_group
from sc;
思路:
-- 先给员工薪水分成2组
select *,
ntile(2) over(order by salary) as ranks
from employees
-- 筛选薪水前50%的员工的序号
select * from (
select *, ntile(2) over(order by salary) as ranks from employees
) t
where ranks = 2
nth_value()
函数用于返回分组内到当前行的第N行的值。如果第N行不存在,则函数返回NULL。
N必须是正整数,例如1,2和3。
应用场景: 查询第N名的同学信息
基本形式:
NTH_VALUE(expression, N)
OVER (
[PARTITION BY <part_by_condition>]
[ORDER BY <order_by_list> ASC|DESC]
[rows between ?? And ??]
)
NTH_VALUE(expression, N)
表示在 expression
里第 N
行
select *,
nth_value(score, 1) over(partition by cid order by score desc) as 1th,
nth_value(score, 2) over(partition by cid order by score desc) as 2th,
nth_value(score, 3) over(partition by cid order by score desc) as 3th
from sc;
select *,
nth_value(score, 1) over(partition by cid) as 1th,
nth_value(score, 2) over(partition by cid) as 2th,
nth_value(score, 3) over(partition by cid) as 3th
from sc;
应用:获取各班分数第一名的同学id
思路:
-- 先获取每个班第一名的分数
select *,
nth_value(score,1) over(partition by cid order by score desc) as 1th_score
from sc;
-- 根据分数获得同学信息
select sid, cid, score from (
select *,
nth_value(score,1) over(partition by cid order by score desc) as 1th_score
from sc) t
where score=1th_score
参考来源:
MySQL模块:开窗函数
SQL中开窗函数first_value() 和 last_value()
MySQL8中的开窗函数