分割槽函式Partition By的用法

2021-10-07 02:34:09 字數 1264 閱讀 5856

group by是分組函式,partition by是分割槽函式(像sum()等是聚合函式),注意區分。

over(partition by cno order by degree )
先對cno 中相同的進行分割槽,在cno 中相同的情況下對degree 進行排序

例:查詢每名課程的第一名的成績

select	* 

from (select sno,cno,degree,

rank()over(partition by cno order by degree desc) mm

from score)

where mm = 1;

(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;

(3)rank()與row_number()的區別

由以上的例子得出,在求第一名成績的時候,不能用row_number(),因為如果同班有兩個並列第一,row_number()只返回乙個結果。

例:查詢課程號為『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'

(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'

(3)rank()與dense_rank()的區別

由以上的例子得出,rank()和dense_rank()都可以將並列第一名的都查詢出來;但rank()是跳躍排序,有兩個第一名時接下來是第三名;而dense_rank()是非跳躍排序,有兩個第一名時接下來是第二名。

分割槽函式Partition By的用法

group by是分組函式,partition by是分割槽函式 像sum 等是聚合函式 注意區分。over partition by cno order by degree 先對cno 中相同的進行分割槽,在cno 中相同的情況下對degree 進行排序 例 查詢每名課程的第一名的成績 1 使用r...

分割槽函式Partition By的用法

group by是分組函式,partition by是分割槽函式 像sum 等是聚合函式 注意區分。over partition by cno order by degree 先對cno 中相同的進行分割槽,在cno 中相同的情況下對degree 進行排序 例 查詢每名課程的第一名的成績 1 使用r...

詳解partition by和group by對比

今天大概弄懂了partition by和group 程式設計客棧by的區別聯絡。1.group by是分組函式,partition by是分析函式 然後像sum 等是聚合函式 2.在執行順序上,以下是常用sql關鍵字的優先順序 from where group by h ing order by 而...