select TimePhases.name, TimePhases.phase as FromPhase, Again.Phase as ToPhase, TimePhases.starttime as StartTime, Again.EndTime as EndTime , DateDiff(s, TimePhases.StartTime, Again.EndTime) as Elapsed from TimePhases cross apply timePhases Again where TimePhases.name = again.name and TimePhases.Phase <= again.Phase order by TimePhases.Name, FromPhase, ToPhaseAnd here's Brandon's again:
select a.name ,a.phase as fromphase ,b.phase as tophase,a.starttime,b.endtime,DATEDIFF( S,a.starttime,b.endtime) as elapsed from timephases a inner join timephases b on a.name = b.name and a.phase<=b.phase order by a.name,fromphase,tophaseAfter seeing this, I'd likely use a JOIN instead of a CROSS APPLY (just to keep it generic). But here's the part that surprised me a bit. Even though a full scan is involved either way, the CROSS APPLY runs a bit faster - sometimes it was 60 ms verus 70 ms, but had a few times where it was 45-50 ms versus 70 ms.