I am using the following query in an ssrs line chart. It counts how many orders are recorded each month based on each order date.
My problem is that when a month has no orders, rather than saying zero or null it removes the row for that month all together. I would prefer for it to count it as zero but null would be ok too.
Basically, I want to always have twelve rows whether they contain information or not.
How can I fix this? Is there an expression I can use or something? Or am I missing something completely obvious?
SELECT
MONTH(Ord.OrdDate) AS 'MONTH',
COUNT(CASE WHEN @Worker_ID1 IS NULL OR @Worker_ID1 = Worker.ID THEN 1 END) AS 'Worker1',
COUNT(CASE WHEN @Worker_ID2 IS NULL OR @Worker_ID2 = Worker.ID THEN 1 END) AS 'Worker2',
COUNT(CASE WHEN @Worker_ID3 IS NULL OR @Worker_ID3 = Worker.ID THEN 1 END) AS 'Worker3',
COUNT(CASE WHEN @Worker_ID4 IS NULL OR @Worker_ID4 = Worker.ID THEN 1 END) AS 'Worker4',
COUNT(CASE WHEN @Worker_ID5 IS NULL OR @Worker_ID5 = Worker.ID THEN 1 END) AS 'Worker5'
FROM Ord
JOIN Prod ON Ord.Prod_ID = Prod.ID
JOIN ProdType ON Prod.ProdType_ID = ProdType.ID
JOIN Grouping ON Ord.Grouping_ID = Grouping.ID
JOIN Worker ON Grouping.Worker_ID = Worker.ID
WHERE @Year = YEAR(Ord.OrdDate)
AND (@ProdType_ID IS NULL OR @ProdType_ID = ProdType.ID)
GROUP BY MONTH(Ord.OrdDate)
You need a table containing months in order to make this work (or you can use a stored procedure or probably common table expression).
Would ensure you got:
As the above answers mentioned, you will need an outer join and some kind of calendar table. This is untested, but I think will work for you:
that behavior is well defined by SQL construct "Inner join". use left join (or right join, depending on which is correct side) to retrieve null values when the join condition is not satisfied as below (not tested)
Note - i added additional where clause conditions to check on the year function on orddate as this can be null
google for joins SQL and am sure you will find much more quality information than this
Hope this helps
Got it working by removing the where clause and filtering in the count aggregate.
Just copy and paste your query in the place holder and go. You will always get 12 rows only. And there is no need to create any tables too.