How do I get total user count in mySQL by Grouping by month
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.
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.
The NULL results ARE necessary.
How could I achieve that result in mySQL or in 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.