BrotherWind 2019-07-01
--创建测试表 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()重复且不跳数字排序。