我的目标是累计按日期注册的用户数量
这是我的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 - 每个派生表都必须有自己的别名
答案 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进行更正