2016-09-23 56 views
0

讓我們說我有一個表像這樣:SQL名稱值

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運行。

+0

是否DashDB支持窗口的功能呢? –

回答

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

+0

嗨,我不想要最大(價格)...我想要的物品的名稱與最大價格 –

+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

嘗試用下面的查詢

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