sql查询到相同id但不同值的总和?? .... 我正在尝试计算相同id的总和...以下是我的表
id barter_value
2 50,000
2 1,50,000
3 47,000
3 55,000
3 50,00,000
我想输出
id barter_value
2 2,00,000
3 51,00,2000
select a.buyer_id,
a.prod_barter_val
from add_to_cart as a
join(select buyer_id,
sum(prod_barter_val) as total
from add_to_cart group by buyer_id) as b
on a.buyer_id = b.buyer_id;
答案 0 :(得分:2)
您可以这样做:
select buyer_id, sum(prod_barter_val) from add_to_cart group by buyer_id
答案 1 :(得分:1)
你几乎就在那里,只需更改sql语句(b.total
):
select buyer_id,
sum(prod_barter_val) as total
from add_to_cart
group by buyer_id
答案 2 :(得分:1)
SELECT id, SUM(barter_value) as 'total' FROM table GROUP BY id
这是做什么的: 从表中选择所有ID和易货值。然后GROUP BY生效,所有相等的ID都连接成一行。
如果没有SUM,你最终只会在barter_value列中使用一个随机值,但是使用SUM它会将所有行一起添加到ID(单独)并将其放入总列中。