开发者

Month statistics

I have a table in Postgres and MySQL with a 'created_at' column. I w开发者_如何学Goould 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:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜