Given that you are working on SQL 2005, this should work:
DECLARE @Runners TABLE (Id INT, BeginMile INT, EndMile INT) INSERT INTO @Runners VALUES (1,1,5) INSERT INTO @Runners VALUES (1,5,6) INSERT INTO @Runners VALUES (1,6,20) INSERT INTO @Runners VALUES (1,20,25) INSERT INTO @Runners VALUES (1,25,29) INSERT INTO @Runners VALUES (2,1,9) INSERT INTO @Runners VALUES (2,15,20) INSERT INTO @Runners VALUES (3,1,2) INSERT INTO @Runners VALUES (3,6,10) INSERT INTO @Runners VALUES (3,10,12) WITH OrderedUsers AS ( SELECT * , ROW_NUMBER() OVER (PARTITION BY Id ORDER BY BeginMile) RowNum FROM @Runners ) SELECT a.Id [User] , a.BeginMile PrevBeginMile , a.EndMile PrevEndMile , b.BeginMile AfterBeginMile , b.EndMile AfterEndMile , b.BeginMile - a.EndMile Gap FROM OrderedUsers a JOIN OrderedUsers b ON a.Id = b.Id AND a.EndMile <> b.BeginMile AND a.RowNum = b.RowNum - 1
source share