The above code gets the largest gap of all time (including 2020 and 2021).The following code gives the maximum gap for 2020 and 2021 alone, please refer to:
;WITH cte
as(select *,(12-COUNT(InvoiceMonthNumber) OVER(PARTITION BY InvoiceYear)) gaps,
LEAD(InvoiceMonthNumber) OVER(PARTITION BY InvoiceYear ORDER BY InvoiceMonthNumber) ll,
(LEAD(InvoiceMonthNumber) OVER(PARTITION BY InvoiceYear ORDER BY InvoiceMonthNumber)-
InvoiceMonthNumber) diff
from #tempa)
,cte2 as(select *,(count(diff) over(partition by InvoiceYear)+1) consecutivemonths
from cte
where diff=1)
select '2020' [year],ClientName,max(consecutivemonths) maxconsecutivemonths,max(gaps) maxgap
from cte2
where InvoiceYear=2020
group by ClientName
union all
select '2021',ClientName,max(consecutivemonths) maxconsecutivemonths,max(gaps) maxgap
from cte2
where InvoiceYear=2021
group by ClientName
Ouput: