Hi @Olsson Arne ,
Your rule description is not very clear. In this example, there are many ways to find 3, 4, 8, 10, and 11, but these methods may not apply to all the data in your table. So if this does not solve your problem, then please post more detailed rules.
Please refer to:
Create Table #Sample(Rownr int, Level int);
Insert #Sample(Rownr, Level) Values
(1, 1),
(2, 2),
(3, 3),
(4, 3),
(5, 2),
(6, 3),
(7, 4),
(8, 5),
(9, 4),
(10, 5),
(11, 5);
;With cte As
(Select Rownr, Level,(Rownr-Level) diff
From #Sample )
,cte2 as
(select diff,max(Rownr) Rownr from cte group by diff)
select Rownr from cte2
Drop Table #Sample
Best Regards
Echo
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.