2

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 中实现该结果?

4

3 回答 3

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
于 2012-04-04T17:35:48.657 回答
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 | 
于 2012-04-04T17:44:22.393 回答
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

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

于 2012-04-04T17:41:43.843 回答