如何在查询中计数时显示0

时间:2013-09-13 11:11:27

标签: sql sql-server

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

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

如何编写查询?

1 个答案:

答案 0 :(得分:3)

那是因为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

有许多特定于数据库的方法可以进行查询,但我认为如果您经常需要执行此类查询,最好的方法是创建静态1900-01-01表,用日期填充它(从,例如3000-01-01Date 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

并使用它:

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

还请注意日期的ISO 8601格式。

如果您不太关心性能,可以使用recursive common table expression

{{1}}