this should help:declare @table table (job varchar(10), job_start_dt datetime, job_end_dt datetime)insert into @tableselect 'aaa01', '01/01/2004 20:00', '01/01/2004 20:30' union all select 'aaa02', '01/01/2004 20:34', '01/01/2004 21:45' union all select 'aaa03', '01/01/2004 21:50', '01/01/2004 22:15' union all select 'aaa04', '01/01/2004 22:35', '01/01/2004 23:05'select coalesce(datediff(n, t1.job_end_dt, (select top 1 job_start_dt from @table where job > t1.job)),0) as diff from @table t1
Go with the flow & have fun! Else fight the flow