mysql dense_rank_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()重复且不跳数字排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值