MySQL分组排序求Top N

表结构
MySQL分组排序求Top N

 

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


MySQL分组排序求Top N
 

 

源代码:

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中可以通过子查询创造一个新的变量来过滤。


 

你可能感兴趣的:(mysql)