首页 > 数据库技术 > 详细

MySql某一列累计查询

时间:2017-07-30 09:45:54      阅读:464      评论:0      收藏:0      [点我收藏+]

问题:有一列数据,需要累计显示出来

比如: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

 

MySql某一列累计查询

原文:http://www.cnblogs.com/Iqiaoxun/p/7258174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!