A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @Satnam Nandra ,
Please refer below updated one and check whether it is helpful to you.
;with cte as(
select ID,MonthName,score,1 as ChainLength
from @tmp
where ID = (select min(ID) from @tmp)
union all
select cur.ID,cur.MonthName,cur.score
,case when cur.score < prev.score then prev.ChainLength + 1 else 1 end
from cte prev
join @tmp cur
on prev.ID + 1 = cur.ID
)
,cte1 as (
select a.MonthName StartDate ,b.MonthName EndDate ,b.ChainLength from cte a
inner join (select * from cte where ChainLength>=2) b on a.ID+b.ChainLength-1=b.ID)
select * from cte1 a
where ChainLength=
(select max(ChainLength) from cte1 b where b.StartDate=a.StartDate group by StartDate)
Output:
StartDate EndDate ChainLength
May 2020 Jun 2020 2
Jul 2020 Dec 2020 6
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.