[英]Get N per group MYSQL
问题不在于 : 在GROUP BY中使用LIMIT获得每个组N个结果?
但我承认这是相似的。
我需要选择每人前2行。 行按收到年份排序
问题:同一个月可能输入了2个数据(输入的日期为YYYY-MM)
我附带的查询(在提到的问题之后)被卡在BIG循环中。
SELECT *
FROM `table_data` as b
WHERE (
SELECT count(*) FROM `table_data` as a
WHERE a.Nom = b.Nom and a.year < b.year
) <= 2;
样本数据 :
A | year | Nom
---------------------
b | 2011-01 | Tim
---------------------
d | 2011-01 | Tim
---------------------
s | 2011-01 | Tim
---------------------
a | 2011-03 | Luc
---------------------
g | 2011-01 | Luc
---------------------
s | 2011-01 | Luc
应出口:
A | year | Nom
---------------------
b | 2011-01 | Tim
---------------------
d | 2011-01 | Tim
---------------------
a | 2011-03 | Luc
---------------------
g | 2011-01 | Luc
( -- First get a set of results as if you only wanted the latest entry for each -- name - a simple GROUP BY from a derived table with an ORDER BY SELECT * FROM ( SELECT * FROM `table_data` ORDER BY `year` DESC ) `a` GROUP BY `Nom` ) UNION ( -- Next union it with the set of result you get if you apply the same criteria -- and additionally specify that you do not want any of the rows found by the -- first operation SELECT * FROM ( SELECT * FROM `table_data` WHERE `id` NOT IN ( SELECT `id` FROM ( SELECT * FROM `table_data` ORDER BY `year` DESC ) `a` GROUP BY `Nom` ) ORDER BY `year` DESC ) `b` GROUP BY `Nom` ) -- Optionally apply ordering to the final results ORDER BY `Nom` DESC, `year` DESC
我确信可以用一种更短的方法来完成此操作,但是现在我无法一生解决它的问题。 但这确实有效 -假设您有一个主键(应有)并且它称为id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.