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)
Saya tidak yakin apakah StaffID dan BranchID dapat bervariasi di tabel @results, jadi Anda mungkin perlu mengubah ini jika bisa.