Reputation: 581
How do I count the number of results from MySql database for every month in the past year wherein there might not exist a record for a specific month but it would show zero as the count? For instance, I would like to count the number of registrations that occurred every month, and include those results too where no registrations occurred.
Month Count 1 4 2 2 . . . . 6 0 . . . .
Upvotes: 1
Views: 951
Reputation: 581
While although a lot of answers exist, I found most of them difficult to read and understand. However, using derived tables, I think it's easier to do so with the given query below, where we are trying to count the number of registrations for the past 12 months from user table:
select derived.mm as month, count(u.reg_date) as count from (
SELECT 1 mm UNION ALL SELECT 2 UNION ALL SELECT 3
UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7
UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11
UNION ALL SELECT 12
) derived
left join user u
on derived.mm = month(reg_date)
and u.reg_date > LAST_DAY(DATE_SUB(curdate(),INTERVAL 1 YEAR))
group by derived.mm
HOW THIS WORKS
Hope this comes to help someone out.
Upvotes: 2