如何通过查询获得这些结果:
Id --- Brand --- Price
1 -----Hp -------100
2 -----Hp -------200
3 -----Hp -------300
4 -----Acer -------100
5 -----Acer -------120
进入这些:
Id --- Brand --- Total Price
1 -----Hp -------600
2 -----Hp -------600
3 -----Hp -------600
4 -----Acer -------220
5 -----Acer -------220
品牌和ID必须如此显示。
答案 0 :(得分:1)
你可以试试这个
SELECT
Id
,Brand
,(SELECT SUM(Price) FROM yourtable tb2 WHERE tb1.Brand = tb2.Brand) as TotalPrice
FROM yourtable tb1
答案 1 :(得分:0)
您也可以使用JOIN
获得所需的结果
步骤1-首先尝试使用以下查询获取所需值的SUM
SELECT id, brand, SUM( price ) AS price
FROM `items` group by brand
输出
id brand price
4 Acer 220
1 HP 600
步骤2-现在对基表应用LEFT join以获得最终结果
SELECT t1.id, t1.brand, t2.price
FROM `items` t1
LEFT JOIN (
SELECT id, brand, SUM( price ) AS price
FROM `items`
GROUP BY brand
)t2 ON t1.brand = t2.brand
输出
id brand price
1 HP 600
2 HP 600
3 HP 600
4 Acer 220
5 Acer 220