sql排序之rank,row_number,dense_rank的区别
--创建测试表 create table te.sc(id int, name varchar(20),class varchar(20), score int); --给测试表插入数据 insert into te.sc values (1,'张飞','一年一班',100); insert into te.sc values (2,'刘备','一年一班',99); insert into te.sc values (3,'李逵','一年一班',95); insert into te.sc values (4,'小动','一年一班',97); insert into te.sc values (5,'小智','一年一班',80); insert into te.sc values (6,'吕布','一年二班',67); insert into te.sc values (7,'赵云','一年二班',90); insert into te.sc values (8,'典韦','一年二班',89); insert into te.sc values (9,'关羽','一年二班',70); insert into te.sc values (10,'马超','一年二班',98); insert into te.sc values (11,'张媛','一年一班',100);
不管在oracle,还是在8.0版的mysql中,在排序的时候都可以用到三个函数:rank,row_number,dense_rank
--列出每个班分数排名前三的学生 select * from (select id, name, class, score , row_number() over (partition by class order by score desc) as r1, rank() over (partition by class order by score desc) as r2 , dense_rank() over (partition by class order by score desc) as r3 from te.sc) B where r1<=3 ; id name class score r1 r2 r3 1 张飞 一年一班 100 1 1 1 11 张媛 一年一班 100 2 1 1 2 刘备 一年一班 99 3 3 2 10 马超 一年二班 98 1 1 1 7 赵云 一年二班 90 2 2 2 8 典韦 一年二班 89 3 3 3
这三个函数的区别主要在分数一致的情况下,row_number()不重复排序,rank()重复且跳数字排序,dense_rank()重复且不跳数字排序。
相关推荐
dreamhua 2020-05-10
dreamhua 2020-05-08
liuyang000 2020-04-25
xuanlvhaoshao 2020-02-20
elitechen 2020-02-15
xuanlvhaoshao 2020-01-23
xiaopang 2020-01-05
liuyang000 2019-12-24
dreamhua 2019-12-17
一对儿程序猿 2019-10-30
dreamhua 2019-10-28
Phplayers 2016-04-02
Unfinishcode 2019-07-12
li00lee 2012-11-06
wangxingg 2015-10-22
zjyzz 2014-12-08
Wlitttle 2015-03-30
zjyzz 2011-01-29