This solution is not nearly as efficient as the 2005 (and greater) ranking functions but it is one way:create table #t (ident int identity(1,1), id int, batch varchar(5))insert #t (id, batch)select id, batchfrom testorder by batch, idselect sno = t.ident - (select min(z.ident) from #t z where z.batch = t.batch) + 1 ,id ,batchfrom #t tOUTPUT:sno id batch----------- ----------- -----1 1 abc2 1 abc3 2 abc4 2 abc5 3 abc1 1 pqr2 2 pqr3 2 pqr1 1 xyz2 1 xyz3 2 xyz4 2 xyz5 3 xyz
Be One with the OptimizerTG