在没有数据的柱形图中显示月份

时间:2014-12-05 19:41:02

标签: sql sql-server ssrs-2008-r2

我有一个SSRS柱形图,其中包含两个x轴类别组,它们首先根据年份对数据进行排序,然后是日期。我还在图表上有一个参数,最终用户可以选择他们希望查看数据的月份,图表显示与该月相关的任何数据。我要做的是让图表显示所有月份的列,即使当月没有可用的信息(理想情况下,我希望本月显示0是没有数据),而不是只有基于过滤器的数据的月份。这是我在数据集中的查询:

SELECT COUNT(c.statecodename) AS codename,
         c.statecodename,
         DATENAME(mm, c.expireson) AS Month,
         DATENAME(yyyy, c.expireson) AS Year,
         DATEPART(yyyy, c.expireson) AS YearNum,
         DATEPART(m, c.expireson) AS MonthNum

FROM Table1 AS c

WHERE (c.expireson IS NOT NULL) 
AND (DATENAME(mm, c.modifiedon) IN (@ReportParameter1))


GROUP BY DATENAME(mm, c.expireson), 
               DATENAME(yyyy, c.expireson),
               DATEPART(yyyy, c.expireson), 
               DATEPART(m, c.expireson),
               c.statecodename

UNION ALL

SELECT COUNT(d.statecodename) AS codename,
         d.statecodename collate DATABASE_DEFAULT,
         DATENAME(mm, d.expireson) AS Month,
         DATENAME(yyyy, d.expireson) AS Year,
         DATEPART(yyyy, d.expireson) AS YearNum,
         DATEPART(m, d.expireson) AS MonthNum

FROM Table2 AS d

WHERE (d.expireson IS NOT NULL) 
AND (DATENAME(mm, d.modifiedon) IN (@ReportParameter1))

GROUP BY DATENAME(mm, d.expireson), 
          DATENAME(yyyy, d.expireson), 
          DATEPART(yyyy, d.expireson), 
          DATEPART(m, d.expireson), 
          d.statecodename

ORDER BY YearNum, MonthNum

有没有一种方法可以将空值分配给剩下的几个月,以便它们在柱形图中显示?到目前为止,我已经尝试创建一个检索所有月份的数据集,并使用查找表达式作为我的月参数,但这没有做任何事情。我还尝试检查我的WHERE子句中的DATENAME(mm,c.expireson)IS NULL但是这也没有用。谁能为我提供一个如何实现这一目标的方法?提前谢谢!

1 个答案:

答案 0 :(得分:0)

创建一个包含年份和月份的临时表或变量表:

从该表中选择您的年份和月份,并使用左连接查看您在上面列出的年份和月份的查询。

declare @date as datetime
declare @forecast TABLE ([yy] int, [mm] varchar(15))
set @date = getdate()
While (select datediff(m,@date,getdate())) > -12
Begin
Insert into @forecast (yy, mm) values (datepart(year,@date),datename(month,@date))
set @date = dateadd(m,-1,@date)
IF (select datediff(m,@date,getdate())) > 23
Break
Else
Continue
END

SELECT f.yy, f.mm,
a.codename, 
a.statecodename
FROM @forecast f
LEFT OUTER JOIN
(
SELECT COUNT(c.statecodename) AS codename,
         c.statecodename,
         DATENAME(mm, c.expireson) AS Month,
         DATENAME(yyyy, c.expireson) AS Year
FROM Table1 AS c

WHERE (c.expireson IS NOT NULL) 
AND (DATENAME(mm, c.modifiedon) IN (@ReportParameter1))

GROUP BY DATENAME(mm, c.expireson), 
         DATENAME(yyyy, c.expireson),
         c.statecodename

UNION ALL

SELECT COUNT(d.statecodename) AS codename,
         d.statecodename collate DATABASE_DEFAULT,
         DATENAME(mm, d.expireson) AS [Month],
         DATENAME(yyyy, d.expireson) AS [Year]

FROM Table2 AS d

WHERE (d.expireson IS NOT NULL) 
AND (DATENAME(mm, d.modifiedon) IN (@ReportParameter1))

GROUP BY DATENAME(mm, d.expireson), 
          DATENAME(yyyy, d.expireson), 
          d.statecodename
          ) a
 on f.yy = a.[year] and f.mm = a.[month]