mysql sql:如何累积计数? (总和)

时间:2016-10-01 21:21:12

标签: mysql sql

我的目标是累计按日期注册的用户数量

这是我的mysql sql

SELECT MONTH( DATE ) AS `month`, COUNT(userid) 
FROM  `stats` 
WHERE  `userid` = 1
GROUP BY `month`

这给了我每月的用户数量,但没有累积它们

结果:

month 1 : 90
month 2 : 50 (it should be 90 + 50)
month 3 : 10 (it should be 90 + 50 + 10)

我试过了:

SELECT month,
       SUM( CNT ) AS CUM_CNT_TILL_NOW
  FROM  (
        SELECT MONTH( DATE ) AS `month`, COUNT(userid) AS CNT
          FROM  `stats` 
         WHERE  `userid` = 1
         GROUP BY `month`
      );

并出现错误:#1248 - 每个派生表都必须有自己的别名

4 个答案:

答案 0 :(得分:2)

在MySQL中,基本上有三种方法可以进行累积求和:

  • 相关子查询。
  • 不平等加入聚合。
  • 变量。

后者是最简单的。但是,由于group by在MySQL中的工作方式,通常需要子查询:

SELECT yyyy, mm, cnt,
       (@sum := @sum + cnt) as cume_sum
FROM (SELECT YEAR(DATE) as yyyy, MONTH( DATE ) AS mm, COUNT(userid) AS CNT
      FROM stats
      WHERE userid = 1
      GROUP BY yyyy, mm
     ) ym CROSS JOIN
     (SELECT @sum := 0) params
ORDER BY yyyy, mm;

注意:

  • 这明智地考虑到了这一年。这通常是在你按月累积的时候。
  • @sum变量在查询中定义。这是一种便利。
  • 需要使用子查询,因为有时变量无法按预期使用聚合。
  • 子查询有一个别名。

答案 1 :(得分:0)

SELECT month,
       SUM( CNT ) OVER ( ORDER BY month ROWS BETWEEN UNBOUNDED PRECEEDING  
                         AND CURRENT ROW 
                        ) AS CUM_CNT_TILL_NOW
  FROM
     (
        SELECT MONTH( DATE ) AS `month`, COUNT(userid) AS CNT
          FROM  `stats` 
         WHERE  `userid` = 1
         GROUP BY `month`
      );

另一种解决方案: -

WITH tmp AS 
(
  SELECT MONTH( DATE ) AS `month`, COUNT(userid) AS CNT 
    FROM  `stats` 
   WHERE  `userid` = 1
  GROUP BY `month`
 )
SELECT o.month, o.cnt , RunningTotal = o.cnt + COALESCE(
(
  SELECT SUM(cnt) AS cnt
    FROM tmp i
    WHERE i.month < o.month), 0
)
FROM tmp AS o
ORDER BY o.month;

答案 2 :(得分:0)

在Mysql中,您可以使用会话变量。如下所示:

SET @sum = 0;
SELECT MONTH( DATE ) AS `month`, @sum:=@sum+COUNT(userid) as sum
FROM  `stats` 
WHERE  `userid` = 1
GROUP BY `month`;

否则,你将不得不加入这两个表,但效率很低。

答案 3 :(得分:0)

尝试使用类似的东西:

SELECT MONTH(DATE) AS `month`, COUNT(userid) , (SELECT COUNT(userid) 
    FROM  `stats` 
    WHERE  `userid` = 1 AND MONTH(date) <= MONTH(s.date))
FROM  `stats` s
WHERE  `userid` = 1
GROUP BY `month`

感谢jpw进行更正