--建立測試表 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_rankmysql
--列出每一個班分數排名前三的學生 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()重複且不跳數字排序。sql