那是因为你没有记录BILLS
(BILLDATE = '2013-09-02'
我想这WHERE BILLDATE >='08/01/2013' AND BILLDATE<='09/09/2013'
是一个错字,你想写WHERE BILLDATE >='01/09/2013' AND BILLDATE<='03/09/2013'
有许多特定于数据库的方法可以进行查询,但我认为如果您必须经常进行此类查询,最好的方法是创建静态DATES
表,并用日期填充它(例如 from,例如1900-01-01
until 3000-01-01
):
Date
1900-01-01
1900-01-02
1900-01-03
...
2010-01-01
...
并像这样使用它:
select
d.DATE,
count(b.BILLDATE) as cnt
from DATES as d
left outer join BILLS as b on b.BILLDATE = d.DATE
where d.DATE >='2013-09-01' and d.DATE <= '2013-09-03'
group by d.DATE
另请注意日期的ISO 8601格式。
如果您不太关心性能,可以使用递归公用表表达式:
with cte([Date]) as (
select convert(date, '20130901', 112) -- Start date
union all
select dateadd(dd, 1, [Date])
from cte
where [Date] < '20130903' -- End date
)
select
c.[Date],
count(b.BILLDATE) as cnt
from cte as c
left outer join BILLS as b on b.BILLDATE = d.DATE