1. 程式人生 > >分割槽函式Partition By、帶行號row_number()、排序rank()的用法詳解

分割槽函式Partition By、帶行號row_number()、排序rank()的用法詳解

partition by關鍵字是分析性函式的一部分,它和聚合函式不同的地方在於它能返回一個分組中的多條記錄,而聚合函式一般只有一條反映統計值的記錄,partition by用於給結果集分組,如果沒有指定那麼它把整個結果集作為一個分組,分割槽函式一般與排名函式一起使用。

準備測試資料:

複製程式碼

create table Student  --學生成績表
(
 id int,  --主鍵
 Grade int, --班級
 Score int --分數
)
go

insert into Student values(1,1,88)
insert into Student values(2,1,66)
insert into Student values(3,1,75)
insert into Student values(4,2,30)
insert into Student values(5,2,70)
insert into Student values(6,2,80)
insert into Student values(7,2,60)
insert into Student values(8,3,90)
insert into Student values(9,3,70)
insert into Student values(10,3,80)
insert into Student values(11,3,80)

複製程式碼

一、分割槽函式Partition By的與row_number()的用法

1、不分班按學生成績排名

select *,row_number() over(order by Score desc) as Sequence from Student

執行結果:

2、分班後按學生成績排名

select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student

執行結果:

3、獲取每個班的前1(幾)名

select * from
(
select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student
)T where T.Sequence<=1

執行結果:

 

二、分割槽函式Partition By與排序rank()的用法

1、分班後按學生成績排名 該語句是對分數相同的記錄進行了同一排名,例如:兩個80分的並列第2名,第4名就沒有了

select *,rank() over(partition by Grade order by Score desc) as Sequence from Student

執行結果:

2、獲取每個班的前2(幾)名 該語句是對分數相同的記錄進行了同一排名,例如:兩個80分的並列第2名,第4名就沒有了

select * from
(
select *,rank() over(partition by Grade order by Score desc) as Sequence from Student
)T where T.Sequence<=2

執行結果: