SQL:查找每组的最大记录数

时间:2010-04-17 06:19:46

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

  

可能重复:
  Retrieving the last record in each group

我有一个表,它有三个字段和数据。

Name  , Top , Total
cat   ,   1 ,    10
dog   ,   2 ,     7
cat   ,   3 ,    20
horse ,   4 ,     4
cat   ,   5 ,    10
dog   ,   6 ,     9

我想为每个Total选择Name值最高的记录,所以我的结果应该是这样的:

Name  , Top , Total
cat   ,   3 ,    20
horse ,   4 ,     4
Dog   ,   6 ,     9

按照名称顺序尝试了小组,但是按照结果给了小组的最高记录。有人可以指导我吗?

3 个答案:

答案 0 :(得分:30)

select
  Name, Top, Total
from
  sometable
where
  Total = (select max(Total) from sometable i where i.Name = sometable.Name)

select
  Name, Top, Total
from
  sometable
  inner join (
    select max(Total) Total, Name
    from sometable
    group by Name
  ) as max on max.Name = sometable.Name and max.Total = sometable.Total

答案 1 :(得分:5)

您可以尝试类似

的内容
SELECT  s.*
FROM    sometable s INNER JOIN
        (
            SELECT  Name,
                    MAX(Total) MTotal
            FROM    sometable
            GROUP BY Name
        ) sMax  ON  s.Name = sMax.Name 
                AND s.Total = sMax.MTotal

答案 2 :(得分:0)

或者使用Exists子句,它返回两个表中唯一存在的行

SELECT * from sometable T
where exists
(select 1
from (SELECT nombre, max(total) as total FROM  sometable TT
    GROUP by nombre) TT
where T.name=TT.name
and T.total=TT.total
)