2016-09-23 62 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