如何包含没有价值的日期

时间:2014-11-20 15:23:44

标签: sql sql-server sql-server-2008

我有一个像这样的查询 -

select CAST(jobrun_proddt as Date) as 'Date', COUNT(*) as 'Error Occurred Jobs' from jobrun
where jobrun_orgstatus = 66 and jobmst_type <> 1
group by jobrun_proddt
order by jobrun_proddt desc

并非每个日期都有计数。我希望能够做的是将数量设为0的空白日期,以便图表看起来像这样 -

2014-11-18  1
2014-11-17  0
2014-11-16  0
2014-11-15  0
2014-11-14  0
2014-11-13  1
2014-11-12  0
2014-11-11  1

目前它没有返回那些没有计数的行。

2014-11-18  1
2014-11-13  1
2014-11-11  1

编辑以添加jobrun表具有所有日期,只有一些日期没有我正在搜索的值。

4 个答案:

答案 0 :(得分:2)

如果您有所有日期的数据,但其他日期正由where子句过滤,那么您可以使用条件聚合:

select CAST(jobrun_proddt as Date) as [Date],
       SUM(CASE WHEN jobrun_orgstatus = 66 and jobmst_type <> 1 THEN 1 ELSE 0
           END) as [Error Occurred Jobs]
from jobrun
group by jobrun_proddt
order by jobrun_proddt desc

答案 1 :(得分:1)

试试这个。使用Recursive CTE生成日期。

WITH cte
     AS (SELECT CONVERT(DATE, '2014-11-18') AS dates --Max date
         UNION ALL
         SELECT Dateadd(dd, -1, dates)
         FROM   cte
         WHERE  dates > '2014-11-11') -- Min date
SELECT a.dates,
       Isnull([Error_Occurred_Jobs], 0)
FROM   cte a
       LEFT JOIN (SELECT Cast(jobrun_proddt AS DATE) AS Dates,
                         Count(*)                    AS [Error_Occurred_Jobs]
                  FROM   jobrun
                  WHERE  jobrun_orgstatus = 66
                         AND jobmst_type <> 1
                  GROUP  BY jobrun_proddt) B
              ON a.dates = b.dates 
         Order by a.dates desc

答案 2 :(得分:0)

您必须使用OUTER JOIN加入表格或生成的连续日期列表,这样对于与您的jobrun_orgstatus不匹配的日期,您可以使用ISNULL或COALESCE返回0.

答案 3 :(得分:0)

首先,您必须指定特定的日期范围 然后你应该把你的桌子与&#34;左连接&#34;

DECLARE @start DATE, @end DATE;
SELECT @start = '20141114', @end = '20141217';

;WITH n AS 
(
  SELECT TOP (DATEDIFF(DAY, @start, @end) + 1) 
    n = ROW_NUMBER() OVER (ORDER BY [object_id])
  FROM sys.all_objects
)

SELECT 'Bob', DATEADD(DAY, n-1, @start) as 'xdate' FROM n;


select CAST(jobrun_proddt as Date) as 'Date', COUNT(*) as 'Error Occurred Jobs' from jobrun
left join n on DATEADD(DAY, n-1, @start) = jobrun.jobrun_proddt
where jobrun_orgstatus = 66 and jobmst_type <> 1
group by jobrun_proddt
order by jobrun_proddt desc