Would this do the trick? i.e. you just want to set IsInAGroup to 1 where there exists a different record which has a start or end period matching the record in question's end or start period:
update a
set IsInAGroup = 1
from myTable a
where exists
(
select top 1 1
from myTable b
where b.Id != a.Id --it's a different record
and
(
b.PeriodEnd = a.PeriodStart --but the record is immediately before our record
or b.PeriodStart = a.PeriodEnd --or the record is immediately after
)
)
Update
Per comments, if you're looking to "squash" a bunch of records into a single one, try going with a recursive CTE.
with cte as
(
--get all periods which don't immediately follow another period
--these are the first record in the group (including groups of 1 record)
--NB: assumes that a single record cannot have its PeriodStart = its own PeriodEnd
select Id, PeriodStart, PeriodEnd, 1 Iteration
from myTable
where PeriodStart not in (select PeriodEnd from myTable)
union all
--recursively get each period with a start date matching the last record's end date.
--persist the original id and start date, use the new record's end date, add 1 to the iteration column each recursion
select cte.Id, cte.PeriodStart, mt.PeriodEnd, cte.Iteration + 1
from cte
inner join myTable mt on mt.PeriodStart = cte.PeriodEnd
)
, cte2 as
(
--get all records / invert the Iteration (so the last record in a window has value r=1)
select id, PeriodStart, PeriodEnd, row_number() over (partition by id order by Iteration desc) r
from cte
)
--select all records where r=1 (i.e. the last created by the recursive cte, giving the largest range of start-to-end date for each id
select Id, PeriodStart, PeriodEnd
from cte2
where r = 1
Hopefully the comments explain what's going on; but if you need any clarifications, please comment.