当前位置:网站首页>Window function row in SQL Server_ number()rank()dense_ rank()

Window function row in SQL Server_ number()rank()dense_ rank()

2022-06-24 10:39:00 Cpsu

Three sorting functions row_number()rank()dense_rank()
about row_number() function , He can sort the table and return a sequence number

create table score
( Student number  nvarchar(10) not null,
 Course  nvarchar(10) not null,
 achievement  nvarchar(10) not null)
insert into score
values('01',' Chinese language and literature ',90),
('01',' mathematics ',67),
('02',' Chinese language and literature ',82),
('02',' mathematics ',78),
('03',' Chinese language and literature ',65),
('03',' mathematics ',98),
('04',' Chinese language and literature ',82),
('04',' mathematics ',98)

For example, the simplest way to sort this table , For example, according to the reverse order of student number

select *,row_number()over(order by  Student number  desc)  Serial number  from score 

 Insert picture description here
Pictured ,row_number()over(order by Field ), Will sort according to the fields you need , And give each line a number , But these numbers are sequential , For example, the student number is 4 No. has two lines , however row_number() The function does not give them the same sequence number, that is, the ranking , That is to say, using this function to sort does not have the same rank . If the values of the data are the same , The first data will rank higher .
row_number() Function can also be used to sort by groups , For example, I want to know the ranking of each course .

select *,row_number()over(partition by  Course  order by  achievement  desc)  ranking  from score 

 Insert picture description here
row_number() over(partition by Field 1 order by Field 2) Can be based on the field 1 Group first and then rank within the group . Again , There will not be the same rank in the case of the same score .

about rank() Functions have a similar usage , Also have rank()over(order by Field ) and rank()() over(partition by Field 1 order by Field 2) Two ways of using , The difference is rank Functions are numbered differently .
I also want to know the ranking of each course .

select *,rank()over(partition by  Course  order by  achievement  desc)  ranking  from score

 Insert picture description here
See the difference ,rank The function will have the same name and times , For example, two are tied for the first place , There is no second place .

about dense_rank() The same is true for functions .

select *,desn_rank()over(partition by  Course  order by  achievement  desc)  ranking  from score

 Insert picture description here
Again ,dense_rank() There will also be times of the same name , But it will continue with the previous number , For example, two tied for the first place will not squeeze out the second place .

原网站

版权声明
本文为[Cpsu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240912595869.html