1

我有一个像这样的简单计数查询

SELECT BILLDATE,COUNT(BILLDATE) AS CNT 
FROM BILLS 
WHERE BILLDATE >='08/01/2013' AND    BILLDATE<='09/09/2013'  GROUP BY BILLDATE

它应该显示

billdate    cnt
01/09/2013   10
02/09/2013    0
03/09/2013    3

但我得到

billdate    cnt
01/09/2013   10
03/09/2013    3

如何编写查询?

4

1 回答 1

3

那是因为你没有记录BILLSBILLDATE = '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-01until 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
于 2013-09-13T11:20:21.563 回答