2010-12-22 102 views
57
Name Value AnotherColumn 
----------- 
Pump 1 8000.0 Something1 
Pump 1 10000.0 Something2 
Pump 1 10000.0 Something3 
Pump 2 3043 Something4 
Pump 2 4594 Something5 
Pump 2 6165 Something6 

我的表看起來像這樣。我想知道如何選擇每個泵的最大值。選擇每個組的最大值

select a.name, value from out_pumptable as a, 
(select name, max(value) as value from out_pumptable where group by posnumber)g where and g.value = value 

這個代碼的工作,但我得到泵1的兩個條目,因爲它有兩個條目具有相同的值。

回答

6
SELECT 
    b.name, 
    MAX(b.value) as MaxValue, 
    MAX(b.Anothercolumn) as AnotherColumn 
FROM out_pumptabl 
INNER JOIN (SELECT 
       name, 
       MAX(value) as MaxValue 
      FROM out_pumptabl 
      GROUP BY Name) a ON 
    a.name = b.name AND a.maxValue = b.value 
GROUP BY b.Name 

請注意,如果您有主鍵,這將更容易。下面是一個例子

​​
+0

啊,當。我讓這個例子太簡單了。有更多的列表,這使它有點複雜>。< – 2010-12-22 14:33:37

+0

如果更多的列只是將它們添加到選擇 – 2010-12-22 14:34:31

130
select name, max(value) 
from out_pumptable 
group by name 
-2
SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN 
     (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2 
    ON t1.ProdId = t2.ProdId 
    AND t1.Quantity = t2.MaxQuantity 
ORDER BY t1.ProdId 

這會給你的想法。

1
select name, value 
from(select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn 
from out_pumptable) as a 
where rn = 1