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

标签 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

最佳答案

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

关于mysql - 为什么 MySQL 累积和会产生错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325157/

相关文章:

mysql - MySQL中MyISAM表中延长某一字段的varchar长度有什么影响?

javascript - 推送到数组并创建运行总计

java - 路径 [/jaagrut] 上下文中 servlet [com.jagrut.GroupServlet] 的 Servlet.service() 抛出异常

php - SQL : Join not working

java - ORA-00936 导致的 "Procedure created with compilation error"

sql - 如何检索到CEO为止的所有监事?

sql - 什么时候需要对主键和外键施加约束?

python - 计算 for 循环期间的运行总计 - Python

python - 累积总和仅适用于 1 列 python

python sql查询说明 'not enough input arguments'