This question already has an answer here:
substitude zeros for missing months in mysql query (1 answer)
Closed last month.
I have a table that looks like this:
ID | Date | Status |
---|---|---|
1 | 2020-10-01 | Silver |
2 | 2021-01-01 | Gold |
3 | 2020-11-01 | Bronze |
1 | 2020-12-01 | Bronze |
1 | 2021-03-01 | Platinum |
2 | 2020-10-01 | Bronze |
3 | 2021-04-01 | Diamond |
2 | 2021-04-01 | Bronze |
1 | 2020-04-01 | Gold |
I need to count the number of customers per status per month, the thing is that the table only shows the entry when the status changed, but I would need to also account for the status for that particular customer on the months prior or after that. For example, ID 1 was Gold before(we can assume because it was the first entry) and on 04\2020, and remained gold until 10\2020 when status changed to Silver, then Silver until 12\2020 when it changed to Bronze and so forth... I would have to account for each customer for those months between the status changes that shows on the table, and I do not know how to do that.
I came up with this query, but it only accounts for the months where there was a status change, basically only the entries that shows on the table:
SELECT FORMAT(Date, 'yyyy-MM') AS Month_Year, Status, COUNT(ID) AS Count_Status
FROM Table1
GROUP BY FORMAT(Date , 'yyyy-MM'), Status
My output should be like:
Month_Year | Status | Count_Status |
---|---|---|
2020\04 | Bronze | 11111 |
2020\04 | Silver... | 22222 |
2020\05 | Bronze | 11111 |
2020\05 | Silver... | 22222 |
2020\05 | Diamond | 33333 |
And so forth...
Can anyone point me to the right direction?
I also have another table that contains two columns, ID and Registration Date for each customer. How would be my approach to basically get the same output as above but this time account for only customer that registered on that particular month?
Thank you!
1条答案
按热度按时间ac1kyiln1#
See example.
First we create calendar table - all month between min and max dates in table, or other date interval.
Then, expand status changes (status,from_date)->(status,from_date,to_date=next_date=next from_date).
Then JOIN Calendar table and expanded status changes table and get status for every Id for every possible months.
For your test data
result is
For the selected report interval, you can modify the query as follows (MySql syntax)
There result is