将缺少的月份添加到查询的结果集中

时间:2014-08-16 22:53:14

标签: sql sql-server reporting-services

首先,我想为标题道歉,这是误导,我真的没有办法解释这个问题,但显示出了什么问题。 我有一个包含3列的表: id - 人的身份 dateInvested InvestedAmount 现在我有这个查询,它检索一年中每个月为特定Id投入了多少钱:

SELECT DATEPART(month, dbo.tblProjectBridge.dateInvested) AS Month
     , SUM(dbo.tblProjectBridge.investmentAmount) AS Amount
FROM dbo.tblProjectBridge 
RIGHT OUTER JOIN dbo.tblInvestor    ON dbo.tblProjectBridge.personId = dbo.tblInvestor.id 
RIGHT OUTER JOIN dbo.tblAgent       ON dbo.tblInvestor.refId = dbo.tblAgent.id 
RIGHT OUTER JOIN dbo.tblSeniorAgent ON dbo.tblAgent.seniorId = dbo.tblSeniorAgent.Id
WHERE (dbo.tblSeniorAgent.Id = @id) 
  AND (DATEPART(year, dbo.tblProjectBridge.dateInvested) = @year)
GROUP BY DATEPART(month, dbo.tblProjectBridge.dateInvested)

现在查询工作正常,问题是我需要将此查询分配给报表服务中的图表,有时在某个月没有投资,因此月份不会出现。 例如,对于一个id,它可能会返回:

month | amount
1     | 12000
5     | 25241
11    | 52124

我甚至想要几个没有投资的月份出现,所以它会这样:

month | amount
1     | 12000
2     | 0
3     | 0
4     | 0
5     | 25241
6     | 0

等等......我如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

查询

;WITH MissingMonths
 AS 
   (
    SELECT number
    FROM master..spt_values
    WHERE number > 0 AND number < 13 
    GROUP BY number
    ),
Your_Query
AS
  (
   -- Inside this CTE you will put you existing query
  SELECT 1 AS [Month], 12000 AS [Amount] 
  UNION ALL SELECT 5, 25241
  UNION ALL SELECT 11,52124
  )
SELECT COALESCE(number,[month]) AS [Month]
      ,COALESCE(amount, 0)      AS Amount
FROM   MissingMonths MM 
LEFT JOIN Your_Query Q   ON MM.number = Q.[month]

结果

╔═══════╦════════╗
║ Month ║ Amount ║
╠═══════╬════════╣
║     1 ║  12000 ║
║     2 ║      0 ║
║     3 ║      0 ║
║     4 ║      0 ║
║     5 ║  25241 ║
║     6 ║      0 ║
║     7 ║      0 ║
║     8 ║      0 ║
║     9 ║      0 ║
║    10 ║      0 ║
║    11 ║  52124 ║
║    12 ║      0 ║
╚═══════╩════════╝