每月总用户数

时间:2012-04-04 17:05:59

标签: mysql count

mySQL总用户数

按月分组

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

嗯,这方面的困难在于我不希望计算月, 的用户数量达到(包括)月份

用户表结构

+---------------+--------------+------+-------------------+----------------+
| Field         | Type         | Null | Default           | Extra          |
+---------------+--------------+------+-------------------+----------------+
| ID            | int(11)      | NO   | NULL              | auto_increment |
| email         | varchar(225) | NO   | NULL              |                |
................................-CUT-.......................................
| registered    | timestamp    | NO   | CURRENT_TIMESTAMP |                |
+---------------+--------------+------+-------------------+----------------+

示例数据

1 example1@mail 2012-04-04 xx:xx:xx
2 example2@mail 2012-05-04 xx:xx:xx
3 example3@mail 2012-05-04 xx:xx:xx

首选输出

+------+-------+-------+
| Year | Month | Count |
+------+-------+-------+
| 2012 | 01    | 0     |
| 2012 | 02    | 0     |
| 2012 | 03    | 0     |
| 2012 | 04    | 1     |
| 2012 | 05    | 3     |
+------+-------+-------+

NULL 结果不是必需的。

我怎样才能在纯mySQL中实现这个结果?

3 个答案:

答案 0 :(得分:3)

我没有试过这个,但这些方面的东西应该有效 -

SELECT tots.*, @var := @var + tots.`count`
FROM (
    SELECT
        YEAR(registered) AS `year`,
        MONTH(registered) AS `month`,
        COUNT(*) AS `count`
    FROM user
    GROUP BY `year`, `month`
) AS tots, (SELECT @var := 0) AS inc

答案 1 :(得分:0)

此方法首先获得发生任何注册的所有月份的第一天。然后它会加入每个注册时间超过该月第一天的用户,然后计算用户数。

SELECT
    YEAR(dates.first_day_of_month) AS registration_year,
    MONTH(dates.first_day_of_month) AS registration_month,
    COUNT(u.ID)
FROM (
    SELECT DISTINCT
        DATE_SUB(
            DATE_ADD(
                DATE_SUB(registered,INTERVAL (DAY(registered)-1) DAY), 
            INTERVAL 1 MONTH), 
        INTERVAL 1 SECOND) first_day_of_month
    FROM user 
) dates 
    LEFT JOIN user u ON u.registered <= dates.first_day_of_month
GROUP BY dates.first_day_of_month

如果您想避免在未发生注册的月份中出现间隙,您可以将子查询替换为使用预先存在的“数字”表的另一个查询来获取所有可能月份的列表。

答案 2 :(得分:0)

您可以使用几个用户变量来执行此操作:

set @c = 0;
set @d = 0;
select y, m, @d := @d + Count as Count from
  (select year(registered) as y, 
     month(registered) as m, 
     @c := @c + count(*) as Count
   from user
   group by y,m) as t;

给你

+------+------+-------+
| y    | m    | Count |
+------+------+-------+
| 2011 |    1 |  2455 | 
| 2011 |    2 | 14253 | 
| 2011 |    3 | 42311 |