MySQL Query按日期范围分组

时间:2013-12-19 19:15:48

标签: 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,其中count是0

1 个答案:

答案 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;