2013-05-08 124 views
2

我有這樣的SQL得到報告:計數組按日期結果爲零

select 
    count(id_reg) total, 
    YEAR(fechaingreso) ano, 
    MONTH(fechaingreso) mes, 
    DAY(fechaingreso) Dia 
from 
    vw_casos_tc 
where 
    fechaingreso between '2012-12-05' and '2013-5-8' 
group by 
    DAY(fechaingreso), MONTH(fechaingreso), YEAR(fechaingreso) 
order by 
    Ano, Mes, dia 

它工作正常節選爲沒有記錄時計數(id_reg)= 0的日子,這天不會出現在我的結果。

total ano  mes  dia 
----------------------------- 
66 2012 12 13 
22 2012 12 14 
23 2012 12 17 

沒有結果(2012 12 15和2012 12 16)。 如何修改我的腳本以獲得總共= 0的這幾天?

+1

您正在使用什麼版本的SQL Server? – Lamak 2013-05-08 17:10:19

+0

沒有結果,因爲你有**沒有記錄**這些日期,對吧? – 2013-05-08 17:11:20

回答

5

這是一種方式,假設的SQL Server 2008(雖然你可以很容易地修改它的SQL Server 2005):

DECLARE @StartDate DATE, @EndDate DATE 
SET @StartDate = '20121205' 
SET @EndDate = '20130508'; 

WITH AllDays AS 
(
    SELECT @StartDate YourDate 
    UNION ALL 
    SELECT DATEADD(DAY,1,YourDate) 
    FROM AllDays 
    WHERE DATEADD(DAY,1,YourDate) <= @EndDate 
) 
SELECT A.YourDate, 
     ISNULL(B.Total,0) Total 
FROM AllDays A 
LEFT JOIN (SELECT CONVERT(DATE,fechaingreso) YourDate, 
        COUNT(id_reg) Total 
      FROM vw_casos_tc 
      WHERE fechaingreso >= @StartDate 
       AND fechaingreso < DATEADD(DAY, 1, @EndDate) 
      GROUP BY CONVERT(DATE,fechaingreso)) B 
    ON A.YourDate = B.YourDate 
OPTION(MAXRECURSION 0)