0

我有下表和一些示例数据。

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数字的最大值的记录。 我似乎遇到问题的部分是获取查询以获取最近更新的 50 个唯一序列号。

下面是我基于这个 StackOverflow question 提出的查询。

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
4

1 回答 1

1

它看起来像一个经典问题,可以通过以下方式解决:

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

于 2013-04-15T20:12:36.597 回答