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)
Nejsem si jistý, zda se StaffID a BranchID mohou lišit v tabulce @results, takže možná budete muset toto upravit, pokud mohou.