如何获得按月计算的总用户数mysql

时间:2017-08-26 17:48:57

标签: php mysql

如何通过按月分组来获取mySQL中的总用户数

我想列出按月分组的注册用户总数。

这方面的困难在于,如果在任何一个月内没有数据,我希望计算范围必须与计数之间的所有月份。

我的代码

SELECT tots.*, @var := @var + tots.`count` as totalCount
  FROM (
     SELECT
        YEAR(registered) AS `year`,
        MONTH(registered) AS `month`,
        COUNT(*) AS `count`
     FROM user where id = 73
          AND registered >= '2017-01-01'
          AND registered <= '2017-05-01'
     GROUP BY `year`, `month`
  )
AS tots, (SELECT @var := 0) AS inc

当前输出

+------+-------+-------+-------------+
| Year | Month | Count | TotalCount  |
+------+-------+-------+-------------+
| 2017 | 01    | 1     | 1           |
| 2017 | 04    | 4     | 5           |
+------+-------+-------+-------------+

首选输出

+------+-------+-------+-------------+
| Year | Month | Count | TotalCount  |
+------+-------+-------+-------------+
| 2017 | 01    | 1     | 1           |
| 2017 | 02    | 0     | 1           |
| 2017 | 03    | 0     | 1           |
| 2017 | 04    | 1     | 2           |
| 2017 | 05    | 0     | 2           |
+------+-------+-------+-------------+

此处计数是该月的新用户总数, TotalCount 是该月的总用户数。

必须使用NULL结果。

我怎样才能在mySQL或Laravel PHP中实现这个结果?

1 个答案:

答案 0 :(得分:0)

据推测,您每月至少注册一个用户。如果是这样,您可以使用条件聚合:

SELECT tots.*, (@var := @var + tots.`count`) as totalCount
FROM (SELECT YEAR(registered) AS `year`, MONTH(registered) AS `month`,
             SUM( id = 73 ) AS `count`
      FROM user 
      WHERE registered >= '2017-01-01' AND registered <= '2017-05-01'
      GROUP BY `year`, `month`
     ) tots CROSS JOIN
     (SELECT @var := 0) AS params;

否则,您需要一个日历表或每月生成一行的方法。