我如何通過按月分組獲得用戶總數count如何獲得月總用戶數mysql
我想列出按月分組的註冊用戶總數。
關於這一點的難點是,如果在任何月份沒有數據,我希望計數必須與計數值爲0的範圍內的所有月份。
我的代碼
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
電流輸出
+------+-------+-------+-------------+
| Year | Month | Count | TotalCount |
+------+-------+-------+-------------+
| 2017 | 01 | 1 | 1 |
| 2017 | 04 | 4 | 5 |
+------+-------+-------+-------------+
首選的輸出
+------+-------+-------+-------------+
| Year | Month | Count | TotalCount |
+------+-------+-------+-------------+
| 2017 | 01 | 1 | 1 |
| 2017 | 02 | 0 | 1 |
| 2017 | 03 | 0 | 1 |
| 2017 | 04 | 1 | 2 |
| 2017 | 05 | 0 | 2 |
+------+-------+-------+-------------+
這裏計數當月是新用戶總數,並且TotalCount是截至該月份的總用戶數。
NULL結果是必需的。
我怎麼能在mySQL或Laravel PHP中實現該結果?
輸出輸出輸出。如何輸入? – Strawberry
@Strawberry我沒有得到你。 – Rajeev
請參閱[爲什麼我應該提供一個用於我認爲是非常簡單的SQL查詢的MCVE](http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for - 什麼似乎對我來說是一個非常簡單的SQL查詢) – Strawberry