jriff
jriff

Reputation: 1977

Month statistics

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)

Upvotes: 1

Views: 1535

Answers (1)

Frank Heikens
Frank Heikens

Reputation: 127116

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:

CREATE TABLE months(nr tinyint);
INSERT INTO months(nr) VALUES (1),(3),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12);

SELECT 
  nr as month, 
  COUNT(*) as c 
FROM 
  sale_registrations 
    RIGHT JOIN months ON EXTRACT(month FROM created_at) = nr
WHERE 
  (created_at BETWEEN '2011-01-01' AND '2011-12-31') 
GROUP BY 
  EXTRACT(month FROM created_at)
ORDER BY 
  EXTRACT(month FROM created_at) ASC;

In PostgreSQL you could use generate_series(), but that's not going to work in MySQL.

Upvotes: 1

Related Questions