当前位置: 移动技术网 > IT编程>数据库>Mysql > 详解MySQL分组排序求Top N

详解MySQL分组排序求Top N

2017年12月07日  | 移动技术网IT编程  | 我要评论

mysql分组排序求top n

表结构

 

按照grp分组,按照num排序,每组取top 3,输出结果如下:


 
 

源代码:

select * from score as t3  
where (  
  select count(*) from score as t1  
  left join score as t2  
  on t1.grp = t2.grp and t1.num < t2.num  
  where t1.id = t3.id 
) < 3 
order by t3.grp asc, num desc 
 

在where中可以通过子查询创造一个新的变量来过滤。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网