group by是分組函數,partition by是分區函數, rank和dense_rank 是排名函數

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章