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中可以通过子查询创造一个新的变量来过滤。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!