mysql对每一行求和

时间:2019-01-21 04:43:38

标签: mysql sum row

查询以获取如下结果

表价( 项目int, 整数, 数量int )

+-------+-------+----------+
| item  | price | quantity |
+-------+-------+----------+
| box 1 |  1000 |        4 |
| box 2 |  2000 |        1 |
| box 3 |  3000 |        6 |
+-------+-------+----------+

结果

+-------+-------+----------+-----------+-------+
| item  | price | quantity | sub total | total |
+-------+-------+----------+-----------+-------+
| box 1 |  1000 |        4 |      4000 | 16000 |
| box 2 |  2000 |        1 |      2000 | 18000 |
| box 3 |  3000 |        6 |     18000 | 36000 |
+-------+-------+----------+-----------+-------+

2 个答案:

答案 0 :(得分:-1)

如果您的mysql版本低于8.0,则可以尝试以下

select 
    item,price,quantity,price*quantity as total, 
    @totalall:= @totalall + price*quantity as TotalAll
from price, (Select @totalall:= 0) as totalall;

或者,如果您的MySQL vsersion 8.0+,则可以在下面尝试-

SELECT 
    item,price,quantity,price*quantity as total, 
    SUM(price*quantity) OVER(ORDER BY item) AS TotalAll
FROM price;

答案 1 :(得分:-1)

从交叉联接(选择@sum:= 0)参数中选择数量,项(@sum:= @ sum +(item * amount))作为“数量”