posts - 85,  comments - 2,  views - 30408
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

group by是分组函数,partition by是分区函数(像sum()等是聚合函数),注意区分。

1、over函数的写法:
over(partition by cno order by degree )
1
先对cno 中相同的进行分区,在cno 中相同的情况下对degree 进行排序

2、分区函数Partition By与rank()的用法“对比”分区函数Partition By与row_number()的用法
例:查询每名课程的第一名的成绩

(1)使用rank()
SELECT *
FROM (select sno,cno,degree,
rank()over(partition by cno order by degree desc) mm
from score)
where mm = 1;
1
2
3
4
5
得到结果:


(2)使用row_number()
SELECT *
FROM (select sno,cno,degree,
row_number()over(partition by cno order by degree desc) mm
from score)
where mm = 1;
1
2
3
4
5
得到结果:


(3)rank()与row_number()的区别
由以上的例子得出,在求第一名成绩的时候,不能用row_number(),因为如果同班有两个并列第一,row_number()只返回一个结果。

2、分区函数Partition By与rank()的用法“对比”分区函数Partition By与dense_rank()的用法
例:查询课程号为‘3-245’的成绩与排名

(1) 使用rank()
SELECT *
FROM (select sno,cno,degree,
rank()over(partition by cno order by degree desc) mm
from score)
where cno = '3-245'
1
2
3
4
5
得到结果:


(2) 使用dense_rank()
SELECT *
FROM (select sno,cno,degree,
dense_rank()over(partition by cno order by degree desc) mm
from score)
where cno = '3-245'
1
2
3
4
5
得到结果:


(3)rank()与dense_rank()的区别
由以上的例子得出,rank()和dense_rank()都可以将并列第一名的都查找出来;但rank()是跳跃排序,有两个第一名时接下来是第三名;而dense_rank()是非跳跃排序,有两个第一名时接下来是第二名。
 
原文链接:https://blog.csdn.net/weixin_44547599/article/details/88764558

posted on   wxm3177  阅读(195)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示