在MySQL中创build一个累积和列

我有一个如下所示的表格:

id count 1 100 2 50 3 10 

我想添加一个名为cumulative_sum的新列,所以表如下所示:

 id count cumulative_sum 1 100 100 2 50 150 3 10 160 

有一个MySQL更新语句,可以很容易地做到这一点? 什么是完成这个最好的方法?

如果性能问题,你可以使用一个MySQLvariables:

 set @csum := 0; update YourTable set cumulative_sum = (@csum := @csum + count) order by id; 

或者,您可以删除cumulative_sum列并在每个查询上计算它:

 set @csum := 0; select id, count, (@csum := @csum + count) as cumulative_sum from YourTable order by id; 

这以运行的方式计算运行总和:)

使用相关查询:


  SELECT t.id, t.count, (SELECT SUM(x.count) FROM TABLE x WHERE x.id <= t.id) AS cumulative_sum FROM TABLE t ORDER BY t.id 

使用MySQLvariables:


  SELECT t.id, t.count, @running_total := @running_total + t.count AS cumulative_sum FROM TABLE t JOIN (SELECT @running_total := 0) r ORDER BY t.id 

注意:

  • JOIN (SELECT @running_total := 0) r是一个交叉连接,允许variables声明而不需要单独的SET命令。
  • MySQL的任何子查询/派生表/内联视图都需要表别名r

注意事项:

  • MySQL的具体; 不能移植到其他数据库
  • ORDER BY是重要的; 它确保顺序匹配OP,并且可以对更复杂的variables使用(IE:psuedo ROW_NUMBER / RANKfunction,MySQL缺less)有更大的影响。
 UPDATE t SET cumulative_sum = ( SELECT SUM(x.count) FROM tx WHERE x.id <= t.id ) 

示例查询

 SET @runtot:=0; SELECT q1.d, q1.c, (@runtot := @runtot + q1.c) AS rt FROM (SELECT DAYOFYEAR(date) AS d, COUNT(*) AS c FROM orders WHERE hasPaid > 0 GROUP BY d ORDER BY d) AS q1 

您也可以创build一个触发器,在每次插入之前计算总和

 delimiter | CREATE TRIGGER calCumluativeSum BEFORE INSERT ON someTable FOR EACH ROW BEGIN SET cumulative_sum = ( SELECT SUM(x.count) FROM someTable x WHERE x.id <= NEW.id ) set NEW.cumulative_sum = cumulative_sum; END; | 

我没有testing过这个

 select Id, Count, @total := @total + Count as cumulative_sum from YourTable, (Select @total := 0) as total ;