You can use the code below to get the required string, however based on your logical string from the next trainer identifier (i.e. 2345) will also be qualified
DECLARE @Trainers TABLE ( TrainerId INT, Start_Time datetime, End_Time datetime ) INSERT INTO @Trainers VALUES (1234,'10-1-2015 08:30','10-1-2015 09:00 '), (1234,'10-1-2015 08:45','10-1-2015 09:15'), (1234,'10-1-2015 09:30','10-1-2015 10:00'), (2345 ,' 10-1-2015 08:45','10-1-2015 09:15'), (2345 ,' 10-1-2015 09:30 ',' 10-1-2015 10:00') ;WITH TrainersTemp AS ( SELECT *, ROW_NUMBER() OVER ( ORDER BY trainerid) AS rn FROM @Trainers ) SELECT CX.TrainerId, CX.Start_Time, CX.End_Time FROM TrainersTemp CX JOIN TrainersTemp CY ON CX.rn = CY.rn + 1 WHERE CY.End_Time < CX.Start_Time
Demo (SQL script disabled again)
or if you want to see all the lines except the erroneous one, use the code below
;WITH TrainersTempAll AS ( SELECT *, ROW_NUMBER() OVER ( ORDER BY trainerid) AS rn FROM @Trainers ) SELECT CX.TrainerId, CX.Start_Time, CX.End_Time FROM TrainersTempAll CX JOIN TrainersTempAll CY ON CX.rn = CY.rn + 1
source share