select
StaffId,
BranchId,
MIN(StartTime),
MAX(EndTime),
PatientId
from
(
select *,
ROW_NUMBER() over (order by starttime)
- ROW_NUMBER() over (partition by isnull(PatientID,-1) order by starttime) rn
from @results
) v
group by staffid, branchid, patientid, rn
order by MIN (starttime)
Jeg er ikke sikker på, om StaffID og BranchID kan variere i @results-tabellen, så du skal muligvis justere dette, hvis de kan.