This solution does more work, which is strictly necessary on the grounds that there may be gaps in the sequence of row values ββand on the assumption that these gaps should be ignored.
Test data setup:
DECLARE @table TABLE (ROW INT, id INT ) INSERT @table SELECT 1,1 UNION SELECT 2,36 UNION SELECT 3,37 UNION SELECT 4,38 UNION SELECT 5,50 UNION SELECT 6,51
Output request
;WITH grpCTE AS ( SELECT ROW, id, ROW_NUMBER() OVER (ORDER BY ROW ) AS rn FROM @table ) ,recCTE AS ( SELECT ROW, id, rn, 1 AS grp FROM grpCTE WHERE rn = 1 UNION ALL SELECT g.row, g.id, g.rn, CASE WHEN g.id = r.id + 1 THEN r.grp ELSE r.grp + 1 END AS grp FROM grpCTE AS g JOIN recCTE AS r ON g.rn = r.rn + 1 ) SELECT row, id, grp FROM recCTE
source share