当前位置: 代码网 > it编程>数据库>Mysql > mysql5.7使用变量进行分组排名并实现筛选

mysql5.7使用变量进行分组排名并实现筛选

2024年05月26日 Mysql 我要评论
概述mysql到8.0之后就有rank和desc_rank函数了,但是在5.7没这玩意,想实现一个分组排名得靠自己手撸了.分组排名student表就id/姓名/分数/班级几个字段,加上class表就i

概述

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

结果

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com