The answer I have is to use
Cursor
I know if there is another solution without a cursor, it will be better for performance aspects
Here is a brief description of my solution:
-- Create DBTest use master Go Create Database DBTest Go use DBTest GO -- Create table Create table Tabletest (nInd int , eq int) Go -- insert dummy data insert into Tabletest (nInd,eq) values (1,0), (2,1), (3,0), (4,1), (5,0), (6,0), (7,0), (8,0), (9,1), (8,0), (9,1) Create table #Tabletest (nInd int ,eq int ,x int ) go DECLARE @nInd int , @eq int , @x int set @x = 1 DECLARE db_cursor CURSOR FOR SELECT nInd , eq FROM Tabletest order by nInd OPEN db_cursor FETCH NEXT FROM db_cursor INTO @nInd , @eq WHILE @@FETCH_STATUS = 0 BEGIN if (@eq = 0) begin insert into #Tabletest (nInd ,eq ,x) values (@nInd , @eq , @x) set @x = @x +1 end else if (@eq = 1) begin insert into #Tabletest (nInd ,eq ,x) values (@nInd , @eq , @x) set @x = 1 end FETCH NEXT FROM db_cursor INTO @nInd , @eq END CLOSE db_cursor DEALLOCATE db_cursor select * from #Tabletest
The end result will be as follows:

Hope this helps.