另一列中具有最高值的SQL名称值

时间:2016-09-23 06:36:57

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

让我说我有一张这样的桌子:

Store    | Item   | Price  
store01  | Apple  | 2.50  
store01  | Pear   | 3.00
store01  | Banana | 3.11  
store02  | Apple  | 2.50  
store02  | Pear   | 2.00
store03  | Banana | 3.10  

我只想要一个查询,列出所有商店,并命名该商店中最昂贵的商品。所以我需要这样的东西:

Store   | Item  
store01 | Banana 
store02 | Apple 
store03 | Banana  

我尝试过这样的事情:

SELECT "Store",
       (case when (max ("Price") = "Price") then "Item" end) as  "Max price Item"   
FROM Table 
group by "Price","Item","Store"; 

但结果只是:

Store   | Max price Item 
store01 | Apple 
store01 | Pear
store01 | Banana
store02 | Apple
store02 | Pear
store03 | Banana

我在dashDB上运行。

3 个答案:

答案 0 :(得分:1)

你应该使用这个

SELECT t.Store,
    t.Item
FROM Table t
INNER JOIN
    (SELECT
        Store,
        MAX(Price) AS max_price
    FROM
        Table 
    GROUP BY 
        Store
    ) mt
ON 
    mt.Store = t.Store
    AND mt.max_price = t.Price;

或者其他方式可能是:

SELECT t.Store,
    t.Item
FROM Table t
WHERE (Store, Price) IN
    (SELECT
        Store,
        MAX(Price) AS max_price
    FROM
        Table 
    GROUP BY 
        Store
    );

答案 1 :(得分:1)

尝试使用以下查询

SELECT Store,Item
  FROM YourTable T,
        (SELECT Store,max(Price) MPrice
         FROM YourTable
          GROUP BY Store
         ) AS T1
  WHERE T1.Store=T2.Store AND T1.Price=T2.MPrice

答案 2 :(得分:1)

以下应该可以解决问题:

 SELECT Store, MAX(Price) FROM Table
 GROUP BY Store

或者

 SELECT
  b.Store,
  MAX(b.Price) as MaxPrice,
  MAX(b.Item) as Item
FROM Table b
INNER JOIN (SELECT 
              Store,
              MAX(Price) as MaxPrice
            FROM Table
            GROUP BY Store) a ON 
a.Store = b.Store AND a.MaxPrice = b.Price
GROUP BY b.Store

示例输入和输出:

sample_input

sample_output