对于简单计数和按日期分组的NULL值,返回0

时间:2014-12-03 01:33:03

标签: sql-server tsql reporting-services ssrs-2008

我正在对SSRS图表进行简单的计数查询,虽然它看起来像一个常见的问题,但我并没有真正找到适合我情况的答案。这是我的问题:

SELECT TOP 30       CAST(qa.Created As Date) As 'Date',
                    COUNT(qa.Created) As 'Count'
FROM                QAs qa
GROUP BY            CAST(qa.Created As Date)
ORDER BY            'Date' DESC

返回类似于:

的内容
Date       | Count

2014-11-10 | 2

2014-11-08 | 3

2014-11-07 | 8

当放入折线图时,在9日没有显示下降到0并且对我的用户来说有点混乱。我想要做的是让所有过去30天都按顺序显示,即使它们是0。我已被告知要使用COALESCE()执行此操作,但我似乎无法获得那工作要么。我哪里错了?

2 个答案:

答案 0 :(得分:4)

使用Recursive CTE生成过去30天的日期。

;WITH cte
     AS (SELECT Cast(dateadd(day,-30,Getdate()) AS DATE) AS dates
         UNION ALL
         SELECT Dateadd(day, 1, dates)
         FROM   cte
         WHERE  dates < cast(Getdate() as date)
SELECT a.Dates           AS [Date],
       Count(qa.Created) AS [Count]
FROM   cte a
       LEFT JOIN QAs qa
              ON a.dates = Cast(qa.Created AS DATE)
GROUP  BY a.Dates 
ORDER  BY a.Dates 

答案 1 :(得分:2)

我可能会使用NoDisplayName的递归CTE,但另一方面,如果你碰巧在2005年之前被困在某些东西中我已经很长时间了。

--Build a table of dates
DECLARE @dates AS TABLE([date] date)
DECLARE @i int

SET @i = 30

WHILE @i > 0
BEGIN
    INSERT INTO @dates([date])
    SELECT DATEADD(d, -1 * @i, GETDATE())
    SET @i = (@i - 1)
END


--Join into those dates so that no date is excluded
SELECT [date], SUM(dateCount)
FROM (
    SELECT d.[date], CASE WHEN qa.Created IS NULL THEN 0 ELSE 1 END AS dateCount
    FROM @dates d
        LEFT JOIN QAs qa ON CAST(qa.Created AS date) = d.[date]
) AS dateCounts
GROUP BY [date]