Assuming that [column] defines the order of your table rows for the purpose of knowning which row is the "previous" row and that [column] values are sequential then this recursive common table expression would work:;with yourTable ([Column], [ID], Condition)as( select 1, 1, 1 union all select 2, 2, 0 union all select 3, 2, 0 union all select 4, 4, 1)--recursive CTE,rCTE ([Column], [ID], Condition)as( select [column] ,[ID] ,Condition from yourTable where [column] = 1 union all select t.[column] ,case when c.condition = t.condition then c.[id] else t.[id] end ,t.condition from rCTE c join yourTable t on t.[column] = c.[column]+1)select * from rCTEOUTPUT:Column ID Condition----------- ----------- -----------1 1 12 2 03 2 04 4 1
Be One with the OptimizerTG