经典排名问题(相同分数是否要并列,排名是否有间隔)
drop table if exists score; create table score( sc_id int primary key not null auto_increment, sc_exam int not null ); insert into score values(1,89),(2,67),(3,78),(4,54),(5,90),(6,67),(7,89),(8,34),(9,88); #要求查询该表信息,同时对成绩进行排名,成绩相同的则并列,然后按排名先后显示出来 select *, rank() over (order by sc_exam desc) as ranking, dense_rank() over (order by sc_exam desc) as dese_rank, row_number() over (order by sc_exam desc) as row_num from score GROUP BY 1 ORDER BY sc_exam desc;
1)rank函数:这个例子中是2位,2位,4位,也就是如果有并列名次的行,会占用下一名次的位置。比如正常排名是1,2,3,4,但是现在前3名是并列的名次,结果是:1,1,1,4。
2)dense_rank函数:这个例子中是2位,2位,3位,也就是如果有并列名次的行,不占用下一名次的位置。比如正常排名是1,2,3,4,但是现在前3名是并列的名次,结果是:1,1,1,2。
3)row_number函数:这个例子中是2位,3位,4位,也就是不考虑并列名次的情况。比如前3名是并列的名次,排名是正常的1,2,3,4。