create table #temp(id int,flag char(1),rnum int)
insert into #temp values (11,'n',1),(11,'n',2)
,(11,'y',3),(11,'n',4)
,(11,'n',5),(11,'y',6)
,(11,'n',7)
;With CTE as
(
select t.*
,isnull(tt.rnum,t.rnum)NewRnum
from #temp t
outer apply(select top 1 rnum from #temp tt
where t.id=tt.id and t.flag=tt.flag and t.rnum=tt.rnum+1
order by rnum)tt
)
select *
,dense_rank()over(order by newRNum)
from CTE
drop table #temp