I would do it with recursive cte as follows:
declare @Dept table (col1 integer, col2 integer) insert into @Dept values(1, 1),(2, 1),(3, 2),(4, 2),(5, 1),(6, 2),(7, 2),(8, 3) ;with a as ( select col1, col2, ROW_NUMBER() over (order by col1) as rn from @Dept), s as (select col1, col2, rn, 1 as dr from a where rn=1 union all select a.col1, a.col2, a.rn, case when a.col2=s.col2 then s.dr else s.dr+1 end as dr from a inner join s on a.rn=s.rn+1) col1, col2, dr from s result: col1 col2 dr
ROW_NUMBER is only required if your col1 values โโare not sequential. If they are, you can use recursive cte right away
source share