MySql某一列累计查询
問題:有一列數據,需要累計顯示出來
比如: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
?
轉載于:https://www.cnblogs.com/Iqiaoxun/p/7258174.html
總結
以上是生活随笔為你收集整理的MySql某一列累计查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [leetcode sort]56. M
- 下一篇: [Codevs] 1014 棋盘染色