如何将SUM聚合并在MySQL中作为总计将其放入新列中?

时间:2013-07-13 09:23:25

标签: mysql sum aggregate

这就是我的表格:

id         amount         price
5          2              10
8          4              30
5          3              20 

这是我想要的结果:

id         amount         price     subtotal     grandtotal
5          2              10          20            80
5          3              20          60
8          4              30         120            120

如果我们使用sum和group by id,它会将id为5的两行分成1行,只计算总计,但我需要像上面一样保留每行的细节。 (无论将80放在第一行还是第二行,无论放在哪里都无关紧要。

这在MySQL可能吗?或者我需要用PHP或其他语言来做?

非常感谢。

亲切的问候, LL

1 个答案:

答案 0 :(得分:0)

效率不高,但有效:

select id, amount, price, amount*price subtotal, 
(select sum(amount*price) from table where id = t.id) grandTotal
from table t