mysql - 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 |
+-------+-------+----------+-----------+-------+
解决方案
如果你的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;
推荐阅读
- php - 检查值是否在数组中并返回其余项目
- ios - SSL Pinning Alamofire 适用于任何证书
- python - 根据python中不同的二进制列创建分类列
- java - 播放框架应用程序路由中断
- java - 如何避免在 Java 中由 math.random 数字创建的数组中创建重复项?
- javascript - EOWEBBROWSER 文件数据追加
- javascript - 如何过滤带有子对象的对象
- javascript - javascript的Document.icon?
- javascript - 使用 ajax 和 XML 创建仪表板
- python - Pandas 使用字典过滤