概述
mysql到8.0之后就有rank和desc_rank函数了,但是在5.7没这玩意,想实现一个分组排名得靠自己手撸了.
分组排名
student
表就id/姓名/分数/班级几个字段,加上class
表就id/name两个字段。
需求是查询每个班级分数排名前三的所有人(不是3个人是所有人)
select @last_class := st.class, case when st.class = @last_class then case when @score = st.score then @rank when ( @score := st.score ) is not null then @rank := @rank + 1 end else @rank := 1 end rank, st.* from student st,( select @score := null, @rank := 0, @last_class := null ) a order by st.class, st.score desc
结果
筛选
#explain select a.id as studentid, name, a.class, a.score from ( select @last_class := st.class, case when st.class = @last_class then case when @score = st.score then @rank when ( @score := st.score ) is not null then @rank := @rank + 1 end else @rank := 1 end rank, st.* from student st,( select @score := null, @rank := 0, @last_class := null ) aa order by st.class, st.score desc ) a where a.rank <= 3
结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论