Name Price qty
Deen $11 150
Ann $12 100
Anthony $13 250
Anthony $13 250
Anthony $14 150
SELECT name, SUM(qty), MIN(price) FROM table GROUP BY name
我需要按名称分组,数量之和,只有最低价格作为示例
示例
Name Price qty
Deen $11 150
Ann $12 100
Anthony $13 500
任何人都可以帮助我使用sql?
答案 0 :(得分:2)
那将是:
SELECT
t.Name,
MinPrices.MinPrice,
SUM(t.qty) AS SumQty
FROM
(SELECT MIN(Price) AS MinPrice, Name FROM t GROUP BY Name) AS MinPrices
LEFT JOIN
t ON MinPrices.Name=t.Name
AND
MinPrices.MinPrice=t.Price
GROUP BY
t.Name
- 请参阅此fiddle
答案 1 :(得分:1)
SELECT
name,
MIN(price),
SUM(qty)
FROM
table
GROUP BY
name
ORDER BY
2
再次查看您的查询。我做了一个像你提议的桌子,做了那个查询,它几乎返回了你想要的结果,除了安东尼总和= 650。
答案 2 :(得分:1)
SELECT
t1.name,
SUM(t1.qty),
t1.price
FROM table t1
WHERE
t1.price = (SELECT MIN(t2.price) FROM table t2 WHERE t1.name = t2.name)
GROUP BY t1.name
ORDER BY t1.price