简体   繁体   English

mysql对每一行求和

[英]mysql sum each row

query to get the results as below 查询以得到如下结果

table price( item int, amount int, quantity int, ) 表格价格(项目int,金额int,数量int,)

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

result 结果

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

You can try below if your mysql version below 8.0 如果您的mysql版本低于8.0,可以尝试以下方法

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

OR if your mysql vsersion 8.0+ then you can try below - 或者,如果您的MySQL vsersion 8.0+,则可以在下面尝试-

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM