Mysql分组排序求topN

表结构

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

源代码

1
2
3
4
5
6
7
8
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

) < 3
ORDER BY t3.grp ASC,num DESC;