;WITH CreateDate AS
(
SELECT DATEPART(mm, vn.Created) AS CreatedMnth,
Count(vn.ncmr) AS CreateCt,
DATEPART(YY,vn.Created) AS yr
FROM viewNCMRs vn
GROUP BY DATEPART(YY,vn.Created),
DATEPART(mm, vn.Created)
)
,
CloseDate AS
(
SELECT DATEPART(mm, vn.DateClosed) AS ClosedMnth,
Count(vn.ncmr) AS CloseCt,
DATEPART(YY,vn.DateClosed) AS yr
FROM viewNCMRs vn
WHERE vn.DateClosed IS NOT NULL
GROUP BY DATEPART(YY,vn.DateClosed),
DATEPART(mm, vn.DateClosed)
)
,
AllMonths AS
(
SELECT 1 AS _Month
UNION ALL
SELECT _Month + 1
FROM AllMonths
WHERE _Month < 12
)
,
ALLYears AS
(
SELECT DATEPART(YY,vn.Created) Yr
FROM viewNCMRs vn
UNION
SELECT DATEPART(YY,vn.DateClosed) Yr
FROM viewNCMRs vn
)
SELECT AY.Yr _Year,
AM._Month,
ISNULL(CD.CreateCt,0) CreateCt,
ISNULL(ClD.CloseCt,0) CloseCt
FROM ALLYears AY
CROSS JOIN AllMonths AM
LEFT JOIN CreateDate CD
ON AY.Yr = CD.yr
AND AM._Month = CD.CreatedMnth
LEFT JOIN CloseDate ClD
ON AY.Yr = ClD.yr
AND AM._Month = ClD.ClosedMnth
WHERE CD.CreateCt IS NOT NULL
OR ClD.CloseCt IS NOT NULL
Try this query. It will give you the expected result. WHERE clause will filter out all the rows where CreateCt and CloseCt count is Zero.