在MySQL中获取GROUP的MAX行

时间:2014-04-30 10:31:35

标签: mysql group-by greatest-n-per-group

我有以下数据:

+---------+----------+----------+--------+
|      id | someId   | number   | data   |
+---------+----------+----------+--------+
|      27 |      123 |        1 | abcde1 |
|      28 |      123 |        3 | abcde2 |
|      29 |      123 |        1 | abcde3 |
|      30 |      123 |        5 | abcde4 |
|      31 |      124 |        4 | abcde1 |
|      32 |      124 |        8 | abcde2 |
|      33 |      124 |        1 | abcde3 |
|      34 |      124 |        2 | abcde4 |
|      35 |      123 |       16 | abcde1 |
|     245 |      123 |        3 | abcde2 |
|     250 |      125 |        0 | abcde3 |
|     251 |      125 |        1 | abcde4 |
|     252 |      125 |        7 | abcde1 |
|     264 |      125 |        0 | abcde2 |
|     294 |      123 |        0 | abcde3 |
|     295 |      126 |        0 | abcde4 |
|     296 |      126 |        0 | abcde1 |
|     376 |      126 |        0 | abcde2 |
+---------+----------+----------+--------+

我希望得到一个MySQL查询,让我获得每个 someId 数字最高行的数据。请注意, id 是唯一的,但数字不是

2 个答案:

答案 0 :(得分:2)

SELECT someid, highest_number, data
FROM test_1
  INNER JOIN (SELECT someid sid, max(number) highest_number 
              FROM test_1
              GROUP BY someid) t 
  ON (someid=sid and number=highest_number)

不幸的是,它效率不高。在Oracle中,可以在没有子查询的情况下使用OVER子句,但MySQL ......

更新1

如果有多个数字最高的实例,则会为每对 someid 数字重新提供几个数据 STRONG>。 为了获得每个 someid 的唯一行,我们应该预先聚合源表,使 someid number 对唯一(参见t1子查询)

SELECT someid, highest_number, data
FROM 
  (SELECT someid, number, MIN(data) data
   FROM test_1
   GROUP BY
   someid, number) t1
INNER JOIN 
  (SELECT someid sid, max(number) highest_number 
   FROM test_1
   GROUP BY someid) t2
ON (someid=sid and number=highest_number)

更新2

可以简化以前的解决方案

SELECT someid,highest_nuimber,
  (select min(data)
   from test_1 
   where someid=t1.someid and number=highest_nuimber)
FROM
   (SELECT someid, max(number) highest_nuimber
    FROM test_1
    GROUP BY someid) t1

如果我们实现了 someid 数字的唯一对,那么可以使用相关子查询。与JOIN不同,如果数字的最高值重复多次,则不会产生额外的行。

答案 1 :(得分:1)

轻微调整Naeel的回答,但只返回任何someId的单个数据结果,即使有平局,也应添加GROUP BY

SELECT t1.someid, t1.number, t1.data
FROM Table1 t1
INNER JOIN (SELECT someId sid, max(number) max_number 
            FROM Table1
            GROUP BY someId) t2 
ON (someId = sid AND number = max_number)
GROUP BY t1.someId

SQL小提琴here