SQL 在另一列中具有最高值的名称值
SQL name value with highest value in another column
假设我有一个 table 像这样:
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 运行。
你应该使用这个
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
);
尝试使用以下查询
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
以下应该可以解决问题:
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
示例输入和输出:
假设我有一个 table 像这样:
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 运行。
你应该使用这个
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
);
尝试使用以下查询
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
以下应该可以解决问题:
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
示例输入和输出: