首页 > 解决方案 > mysql对每一行求和

问题描述

查询得到如下结果

表价格(项目 int,金额 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 |
+-------+-------+----------+-----------+-------+

标签: mysqlsumrow

解决方案


如果你的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;

推荐阅读