2011-02-18 180 views
1

我在Postgres和MySQL中有一個'created_at'列的表。我想它查詢以下:月份統計信息

Month Count 
1  0 
2  0 
3  0 
4  12 
5  15 
... 

誰能咳嗽了一些SQL?請注意,沒有返回行的月份必須列爲0。我有這個:

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) 

回答

1

使用EXTRACT(month FROM created_at)得到月份。這也適用於MySQL。

編輯:使用右連接與上月的數字表:

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; 

在PostgreSQL可以使用generate_series(),但是這不會在MySQL工作。

+0

我知道 - 我只是顯示MySQL版本。真正的問題是獲得空閒的月份。 – jriff 2011-02-18 13:35:48