I have a table in Postgres and MySQL with a ‘created_at’ column. I would like to query it for the following:
Month Count
1 0
2 0
3 0
4 12
5 15
...
Can anyone cough up some sql? Notice that the months with no rows returned must be listed as 0’s. I have this:
SELECT month(created_at) as month, count(*) as c
FROM `sale_registrations`
WHERE (created_at>='2011-01-01' and created_at<='2011-12-31')
GROUP BY month(created_at)
ORDER BY month(created_at)
Use
EXTRACT(month FROM created_at)to get the month. This works in MySQL as well.Edit: Use a RIGHT JOIN on a table with the month numbers:
In PostgreSQL you could use generate_series(), but that’s not going to work in MySQL.