我尝试构建一个查询,显示每个月/每年的用户总数。 我现在的查询向我显示了在任何特定月/年点创建的用户。但我想要的是用户的总和,直到那一点,而不仅仅是在那段时间内创建的用户。 这是表结构:
mysql> desc users;
+-------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| username | int(11) | NO | | NULL | |
| password | varchar(255) | NO | | NULL | |
| email | varchar(255) | NO | | NULL | |
| legajo | int(10) unsigned | NO | | NULL | |
| doc_tipo | varchar(45) | NO | | NULL | |
| doc_nro | int(10) unsigned | NO | | NULL | |
| activo | int(10) unsigned | NO | | 0 | |
| token_actv | varchar(255) | NO | | NULL | |
| token_fecha_envio | datetime | NO | | NULL | |
| created | datetime | YES | | NULL | |
| modified | datetime | YES | | NULL | |
| role | varchar(60) | NO | | usuario | |
| nombres | varchar(255) | YES | | NULL | |
| apellido | varchar(255) | YES | | NULL | |
+-------------------+------------------+------+-----+---------+----------------+
这是查询。
SELECT CONCAT_WS('/',Month(created),YEAR(created)), Count(*)
FROM users
GROUP BY Month(created),YEAR(created)
ORDER BY Month(created) ASC ,YEAR(created) ASC
当前查询的结果如下:
mysql> SELECT CONCAT_WS('/',Month(created),YEAR(created)), Count(*) FROM users GROUP BY Month(created),YEAR(created) ORDER BY Month(created) ASC ,YEAR(created) ASC LIMIT 5;
+---------------------------------------------+----------+
| CONCAT_WS('/',Month(created),YEAR(created)) | Count(*) |
+---------------------------------------------+----------+
| 1/2010 | 79 |
| 1/2011 | 70 |
| 1/2012 | 70 |
| 1/2013 | 80 |
| 1/2014 | 64 |
+---------------------------------------------+----------+
非常感谢任何帮助。
答案 0 :(得分:2)
您需要做的就是使用您拥有的查询作为另一个查询的输入,然后使用mysql变量来保存累积总和 - 假设您将年/月字符串别名为d,并计算您的计数值如c:
select d , @sum := @sum + c as rolling_total from (
SELECT CONCAT_WS('/',Month(created),YEAR(created)) d, Count(*) c
FROM users
GROUP BY Month(created),YEAR(created)
ORDER BY Month(created) ASC ,YEAR(created) ASC
) q cross join (select @sum := 0) qq