如何为每个名称获得最大价值

时间:2012-01-09 09:32:18

标签: mysql sql sql-server sql-server-2008

我有下一张桌子:

命名:历史

id(primary key),name,value

1, dani, 50

2, dani, 100

3, john, 100

4, john, 150

我怎样才能得到每个名字最大的价值,结果将是:

2, dani, 100

4, john, 150

谢谢!

6 个答案:

答案 0 :(得分:5)

select max(id), name, max(value) from history group by name

答案 1 :(得分:3)

SELECT id,name,MAX(value) FROM history GROUP By name;

答案 2 :(得分:3)

SELECT id, name, value
FROM history h
JOIN (
    SELECT name, MAX(value) as value
    FROM history GROUP By name;
) t ON h.name = t.name and h.value = t.value

答案 3 :(得分:0)

有一个小的细微差别:如果在名称组内有两次相同的值,则不应该两次获得此行。 假设您具有相同的值,则应返回最后一个ID:

  SELECT DISTINCT t2.MaxId, h.name, h.value
    FROM history h
    JOIN (
        SELECT name, MAX(value) as value
        FROM history GROUP By name
    ) t ON h.name = t.name and h.value = t.VALUE
    JOIN (
    SELECT MAX(id) MAxid,name,value FROM
    history
    GROUP BY name,VALUE
    ) t2 ON [t2].[name]=[h].NAME AND [t2].[value]=[h].value

但我强烈建议在SQL Server上使用一个窗口函数,例如RANK

;    WITH   C
    AS     (SELECT H.id,
                   H.name,
                   H.value,
                   RANK() OVER (PARTITION BY Name ORDER BY value DESC, id DESC) 
                      AS [ValueRank]
            FROM   history AS H)
    SELECT c.id,
           name,
           c.value
    FROM   c
    WHERE  ValueRank = 1;

上次查询的效果要好得多。

答案 4 :(得分:0)

SELECT id,
       name,
       MAX(value) 
FROM   history 
GROUP BY id,
         name
ORDER BY id

答案 5 :(得分:0)

select T1.*  
from history as T1  
inner join (select MAX(value) as value,name  
         from history
         group by name) as T2
on T1.name = T2.name
and T1.value = T2.value