I think you need to restore the request below
DECLARE @StartDate DATETIME = dateadd(m,-12,getdate()), @EndDate DATETIME = getdate(), @DATE DATETIME
DECLARE @TEMP AS TABLE (MeterReadDate datetime)
SET @DATE = @StartDate
WHILE @DATE <= @EndDate
BEGIN
INSERT INTO @TEMP VALUES ( @DATE)
SET @DATE = DATEADD(MONTH,1,@DATE)
END
SELECT convert(char(7), m.MeterReadDate, 121),count(*)
FROM @TEMP m left join
[Announcement] t
on convert(char(7), t.ExpiryDate, 121) = convert(char(7), m.MeterReadDate, 121)
WHERE (t.ExpiryDate IS NULL OR t.ExpiryDate > dateadd(m,-12,getdate()))
group by convert(char(7), m.MeterReadDate, 121)
order by convert(char(7), m.MeterReadDate, 121)
In the where clause, I added t.ExpiryDate IS NULL, because it will be null for the missing month.
source
share