「52」Mysql Top N问题

问题是这样的:

求不同的age分组,按照createTime正序「从小到大」排序的前N个。

解决办法:

1
2
3
4
5
6
7

SELECT
t1.*
FROM
table_a t1
where (SELECT count(*) + 1 FROM table_a t2 WHERE t2.age = t1.age AND t2.create_time > t1.create_time ) <=1 order by create_time desc

结果:

按照age分组,createTime正序排序的Top 2数据

END