重要:Mysql8.0+版本支持窗口函数。
基础语法
窗口函数中,排序函数分三种:
rank() over(partition by 分区字段 order by 排序字段 desc/asc)
dense_rank()over(partition by 分区字段 order by 排序字段 desc/asc)
row_number()over(partition by 分区字段 order by 排序字段 desc/asc)
- rank()函数,当指定字段数值相同,则会产生相同序号记录,且产生序号间隙。
- dense_rank()函数,当指定字段数值相同,则会产生相同序号记录,且不会产生序号间隙
- row_number()函数,不区分是否记录相同,产生自然序列
窗口函数理解
- over() 用来指定函数执行窗口范围,如果后面括号内无任何内容,则指窗口范围是满足 where 条件所有行。
- partition by,指定按照某字段进行分组,窗口函数是在不同的分组分别执行。不会减少原表中的行数
- order by,指定按照某字段进行排序
关于窗口函数是在不同的分组分别执行,不会减少源表中的行数的理解:
Scores表:
id | class_id | score |
---|---|---|
001 | 1 | 95 |
002 | 2 | 87 |
003 | 1 | 92 |
004 | 3 | 87 |
005 | 1 | 86 |
006 | 2 | 93 |
007 | 3 | 91 |
窗口函数查询:
select class_id,count(id)over(partition by class_id order by class_id) as count from Scores;
结果:
class_id | count |
---|---|
1 | 3 |
1 | 3 |
1 | 3 |
2 | 2 |
2 | 2 |
3 | 2 |
3 | 2 |
group by分组函数查询
select class_id,count(id) as count_id from Scores group by class_id order by class_id;
结果:
class_id | count_id |
---|---|
1 | 3 |
2 | 2 |
3 | 2 |
实例
leetcode题目:求Scores表的分数排序,如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
查询:
select Score,dense_rank()over(order by Score desc) as "Rank" from Scores
结果:
score | Rank |
---|---|
95 | 1 |
93 | 2 |
92 | 3 |
91 | 4 |
87 | 5 |
87 | 5 |
86 | 7 |
转载:https://blog.csdn.net/weixin_38851970/article/details/108344129
查看评论