with events as (select count(distinct b."SubstituteTeacher"), row_number() over (partition by b."SubstituteTeacher" order by d."StartTime") as seq from dbo."Accounts" a
full outer join dbo."WorkContracts" b on a."ID" = b."SubstituteTeacher" .
full outer join dbo."SubstituteTeacherPeriods" c .
on a."ID" = c."SubstituteTeacher" .
full outer join dbo."OrderPeriods" d .
on a."ID" = d."CreatedBy"
full outer join dbo."Addresses" e .
on a."Address" = e."ID"
full outer join dbo."StandardCities" f
on e."City" = f."ID"
full outer join dbo."Orders" g
on d."Order" = g."ID"
where a."ID" != 16 and a."ID" != 11797
and b."WorkContractType" != 3
group by d."StartTime", b."SubstituteTeacher")
select * from events where seq = 1 ;