我有下表和一些样本数据。
Record_ID Counter Serial Owner
1 0 AAA Jack
2 1 AAA Kevin
3 0 BBB Jane
4 1 BBB Wendy
根据与上述类似的数据,我试图为MySQL编写一个SQL查询,获取每Counter
个Serial
个值SELECT *
FROM `history` his
INNER JOIN(SELECT serial,
Max(counter) AS MaxCount
FROM `tracking`
WHERE serial IN (SELECT serial
FROM `history`)
GROUP BY serial
ORDER BY record_id DESC) q
ON his.serial = q.serial
AND his.counter = q.maxcount
LIMIT 0, 50
的记录。 我似乎遇到问题的部分是获取查询以获取最新更新的50个唯一序列号。
以下是我根据this StackOverflow question提出的查询。
{{1}}
答案 0 :(得分:1)
它看起来像一个经典的greatest-n-per-group问题,可以通过以下方式解决:
select his.Record_ID, his.Counter, his.Serial, his.Owner
from History his
inner join(
select Serial, max(Counter) Counter
from History
group by Serial
) ss on his.Serial = ss.Serial and his.Counter = ss.Counter
如果要在数据集上使用特定过滤器,则应在子查询中应用所述过滤器。
另一个来源对此问题有更多解释:SQL Select only rows with Max Value on a Column