MySql某一列累计查询
16lz
2021-01-22
问题:有一列数据,需要累计显示出来
比如:id salary 查询结果:id salary sumSalary
1 10000 1 10000 10000
2 20000 2 20000 30000
3 30000 3 30000 60000
解决方案
1、使用自定义变量
①用 Set 定义变量
mysql> set @sumSalary := 0;
mysql> select id,salary,(@sumSalary := @sumSalary + salary) as sum from tbl_stu order by id asc;
②不适用 Set 定义变量,使用 join
mysql> select id,salary,(@sumSalary := @sumSalary + salary) as sum from tbl_stu a join (select @sumSalary := 0) b order by id asc;
2、使用子查询
mysql> select id,salary,(select sum(salary) from tbl_stu b where b.id <= a.id) sumSalary from tbl_stu a order by id asc;
原文:https://stackoverflow.com/questions/2563918/create-a-cumulative-sum-column-in-mysql
更多相关文章
- 如何检查变量是否与fetch()具有相同的值
- PHP OOP和MySQLi连接=致命错误:调用未定义的方法sqmyli::arrayQu
- 如何将sql查询中的值存储到变量中?
- MySQL 自定义函数.txt
- c语言把mysql数据库语句和变量封装为一个语句
- C标准库中的函数定义在哪里?
- Dojo:不能在AccordionContainer.js中读取未定义的属性“h”。
- Crypto.js:在IE 11中未定义“Uint8ClampedArray”
- Vue自定义指令实现checkbox全选功能