MySQL 用户定义变量 Returns 与 COUNT 一起使用时的错误结果

MySQL User Defined Variables Returns wrong result when used with COUNT

我想查找按月分组的特定年份的注册用户数。 下面是查询

set @numberOfUsers := 0; 
SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers, 
(@numberOfUsers := @numberOfUsers + count(u.id)) as totalUsers 
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate));

但是,我没有得到 totalUsers 的正确结果,它没有添加前几行的结果。

month  |  monthlyUsers  |  totalUsers
10     |       1        |      1
11     |       3        |      3

第 11 个月的 totalUsers 值应该是 4。不确定查询中有什么问题。 有帮助吗?

您应该将您的 GROUP BY 查询嵌入到子查询中,以根据最终结果计算您的 运行 总数,而不是在计数仍然 "being computed" 时计算:

set @numberOfUsers := 0; 
SELECT T.*, (@numberOfUsers := @numberOfUsers + T.monthlyusers) as totalUsers 
FROM  
(
    SELECT month(from_unixtime(u.createdDate)) as month, count(u.id) as monthlyusers
    FROM user u 
    where year(from_unixtime(u.createdDate)) = '2016' 
    group by month(from_unixtime(u.createdDate))
) T;

阅读以下内容:http://dev.mysql.com/doc/refman/5.7/en/user-variables.html

For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second:

以下代码应作为解决方案(使用子查询):

SELECT month(from_unixtime(u.createdDate)) as month, 
       count(u.id) as monthlyusers, 
       (select count(*) from user USER where year(USER.createdDate)='2016' and month(USER.createdDate)<=month(u.createdDate)) as totalUsers
FROM user u 
where year(from_unixtime(u.createdDate)) = '2016' 
group by month(from_unixtime(u.createdDate));