如何选择记录包含GROUP(group by)中的MAX(some_field)

时间:2010-04-13 16:17:43

标签: mysql group-by

SELECT MAX(some_field) FROM table_A GROUP BY another_field

这只获得'some_field'的最大值;我想获得包含MAX(some_field)的整个记录​​。

3 个答案:

答案 0 :(得分:6)

select a.*
from table_A a
inner join (
    SELECT another_field, MAX(some_field) as MaxSomeField
    FROM table_A 
    GROUP BY another_field
) am on a.another_field = am.another_field and a.some_field = am.MaxSomeField

答案 1 :(得分:4)

SELECT
  *
FROM
  table_A
  INNER JOIN (
      SELECT MAX(some_field) AS some_field, another_field
        FROM table_A
    GROUP BY another_field
  ) AS max ON table_A.some_field    = max.some_field
          AND table_A.another_field = max.another_field

请注意,如果another_field不是该组中的唯一值,您将获得多行MAX(some_field)。您必须再次对上述进行分组以摆脱这些“重复”。

答案 2 :(得分:1)

Select * From table_A withMax Where Not Exists
    (Select * From table_A Where some_field > withMax.some_field)

通常情况下,你会用其他一些标准来做这件事,你会想要检查重复项,所以一个现实的例子更像是这样:

Select * From table_A withMax Where account_id = 1234 Not Exists
    (
    Select * 
    From table_A 
    Where account_id = withMax.account_id And 
        (
        some_field > withMax.some_field
        Or (some_field = withMax.some_field And id > withMax.id)
        )
    )