[英]how to get total user count monthwise mysql
How do I get total user count in mySQL by Grouping by month 如何通过按月分组来获取MySQL中的总用户数
I want to list the total count of registered users grouped by month. 我想列出按月分组的注册用户总数。
The difficulty about this is that I want count of all the months between a range necessarily with count as 0 if there's no data during any month. 这样做的困难在于,如果任何月份没有数据,我希望将某个范围之间的所有月份都计数为0。
My code 我的密码
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
Current Output 电流输出
+------+-------+-------+-------------+
| Year | Month | Count | TotalCount |
+------+-------+-------+-------------+
| 2017 | 01 | 1 | 1 |
| 2017 | 04 | 4 | 5 |
+------+-------+-------+-------------+
Preferred Output 首选输出
+------+-------+-------+-------------+
| Year | Month | Count | TotalCount |
+------+-------+-------+-------------+
| 2017 | 01 | 1 | 1 |
| 2017 | 02 | 0 | 1 |
| 2017 | 03 | 0 | 1 |
| 2017 | 04 | 1 | 2 |
| 2017 | 05 | 0 | 2 |
+------+-------+-------+-------------+
Here Count is total new user in that month and TotalCount is total user up to that month. 此处Count是该月的新用户总数, TotalCount是该月之前的总用户数。
The NULL results ARE necessary. NULL结果是必需的。
How could I achieve that result in mySQL or in Laravel PHP? 如何在mySQL或Laravel PHP中实现该结果?
Presumably, you have at least one user registered in each month. 大概您每个月至少注册一个用户。 If so, you can use conditional aggregation:
如果是这样,则可以使用条件聚合:
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;
Otherwise you need a calendar table or a way of generating one row per month. 否则,您需要一个日历表或一种每月产生一行的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.