The usage of the partition function Partition By and row_number() and the usage of sorting rank() are explained in detail (get the first few records in the grouping (partition))

The partition by keyword is part of the analytic function. It differs from the aggregate function in that it can return multiple records in a group, while the aggregate function generally has only one record reflecting the statistical value, and partition by is used to group the result set , if not specified then it treats the entire result set as a group. The partition function is generally used in conjunction with the ranking function.

Prepare test data:

copy code
create  table Student --Student   grade table 
(
 id int ,   --primary keyGrade int , --class 
 Score int --score )
 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)
copy code

1. Usage of partition function Partition By and row_number()

1. Students are ranked according to their grades regardless of class

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

Results of the:

2. Ranking according to students' grades

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

Results of the:

3. Get the top 1 (several) of each class

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

Results of the:

 

2. Usage of partition function Partition By and sorting rank()

1. Ranking according to students' grades after the class is divided. This statement is to rank records with the same score. For example, two 80-point scores are tied for the second place, and the fourth place is gone.

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

Results of the:

2. Get the top 2 (a few) of each class. This statement is to rank the records with the same score. For example, two 80-point scores are tied for the second place, and the fourth place is gone.

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

Results of the:

 

Original address: https://www.cnblogs.com/linJie1930906722/p/6036053.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325385478&siteId=291194637