Reputation: 1066
First i want to apologize for the title, it is misleading, I really have no way to explain the question but show what is the problem. I have a table that contains 3 columns: id - id of person dateInvested InvestedAmount Now i have this query which retrieves for each month in a year how much money was invested for a specific 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)
Now the query works fine, the problem is I need to assign this query to a chart in reporting services and sometimes there are no investments in a certain month so the month does not appear. For example for one id it might return:
month | amount
1 | 12000
5 | 25241
11 | 52124
I want even months that have no investments in them to appear so it would like this:
month | amount
1 | 12000
2 | 0
3 | 0
4 | 0
5 | 25241
6 | 0
and so on... How do i get around doing this?
Upvotes: 1
Views: 4503
Reputation: 69524
;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 ║
╚═══════╩════════╝
Upvotes: 3