If the idx
values are guaranteed to be sequential, then try this:
Select f.val, f.idx first, l.idx last
From @tbl f
join @tbl l
on l.val = f.val
and l.idx > f.idx
and not exists
(Select * from @tbl
Where val = f.val
and idx = l.idx + 1)
and not exists
(Select * from @tbl
Where val = f.val
and idx = f.idx - 1)
and not exists
(Select * from @tbl
Where val <> f.val
and idx Between f.idx and l.idx)
order by f.idx
if the idx
values are not sequential, then it needs to be a bit more complex...
Select f.val, f.idx first, l.idx last
From @tbl f
join @tbl l
on l.val = f.val
and l.idx > f.idx
and not exists
(Select * from @tbl
Where val = f.val
and idx = (select Min(idx)
from @tbl
where idx > l.idx))
and not exists
(Select * from @tbl
Where val = f.val
and idx = (select Max(idx)
from @tbl
where idx < f.idx))
and not exists
(Select * from @tbl
Where val <> f.val
and idx Between f.idx and l.idx)
order by f.idx