分區函數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

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM