2013-12-19 192 views
0

我有這個查詢的一個問題:MySQL查詢按日期範圍組

SELECT 
    YEAR(passDate) as Year, 
    count(*) AS total_amount 
FROM 
    `dsp_drop_pass_details` 
WHERE passDate 
    BETWEEN '2009-01-01' 
    AND '2012-05-01' 
    AND batch='DROPOUT' 
GROUP BY YEAR(passDate) 
ORDER BY YEAR(passDate) 

輸出---

Month  total amount 
2011    30 
2012    20 

但我的願望了賣出期權

Month total amount 
2009   0 
2010   0 
2011   40 
2012   20 

我要0在0計數爲0

回答

0

最簡單的方法窩將會有一張桌子,有所有想要的歲月。

create table Years(yearValue int); 

insert into years values (2001), (2002)..., (2020); 

然後在您的實際表上進行左連接。

SELECT y.yearValue, COALESCE(COUNT(d.id), 0) --assumning you have a field id in dsp_drop_pass_details 
FROM years y 
LEFT join dsp_drop_pass_details d on y.yearValue = YEAR(d.passDate) 
WHERE y.yearValue between 2009 and 2012 
GROUP BY y.yearValue 
ORDER BY y.yearValue;