为什么MySQL累积总和会产生错误的结果

时间:2015-10-25 01:22:50

标签: mysql sql cumulative-sum

我需要找到以下数据的累计总和:

以下查询:

SELECT created, COUNT( * ) 
FROM  `transactions` 
GROUP BY created

给我:

created COUNT( * )  
2015-8-09   1
2015-8-15   1
2015-8-16   2
2015-8-17   1
2015-8-23   1

我试着做累积总和,如:

SELECT t1.created, COUNT( * ) , SUM( t2.totalcount ) AS sum
FROM transactions t1
INNER JOIN (

SELECT id, created c, COUNT( * ) AS totalcount
FROM transactions
GROUP BY created
ORDER BY created
)t2 ON t1.id >= t2.id
GROUP BY t1.created
ORDER BY t1.created

但它给出的结果并不像预期的那样:

created COUNT( * )  sum 
2015-8-09   5   6
2015-8-15   3   4
2015-8-16   6   8
2015-8-17   1   1
2015-8-23   4   5

我如何产生以下结果:

created COUNT( * )  sum 
2015-8-09   1   1
2015-8-15   1   2
2015-8-16   2   4
2015-8-17   1   5
2015-8-23   1   6

2 个答案:

答案 0 :(得分:3)

select tmp.*, @sum := @sum + cnt as cum_sum
from
(
  SELECT created, COUNT( * ) as cnt 
  FROM  `transactions` 
  GROUP BY created
  ORDER BY created
) tmp
cross join (select @sum := 0) s

答案 1 :(得分:2)

您的内部查询是选择ID而不对其进行分组。让我们按照日期重新修改它。

SELECT t1.created, COUNT( * ) AS daycount, SUM( t2.totalcount ) AS sum
  FROM transactions t1
 INNER JOIN ( SELECT created, COUNT( * ) AS totalcount
                FROM transactions
               GROUP BY created
            ) t2 ON t1.created >= t2.created
 GROUP BY t1.created
 ORDER BY t1.created;

或者您可能希望将totalcount放入内联:

SELECT t1.created, COUNT(*) AS daycount
     , ( SELECT COUNT(*) FROM transactions t2
          WHERE t2.created <= t1.created ) AS totalcount
  FROM transactions t1
 GROUP BY created
 ORDER BY CREATED;