After researching SQL SERVER ISLANDS , as suggested by @KM, I came up with the following query, which seems to work well when additional class codes are added to the dataset.
select a.code, a.class, a.txdate as mindate, b.txdate as maxdate from ( --Find minimum island select code , class , txdate , row_number() over (order by code, class, txdate) as n from #items tb1 where not exists ( select * from #items tb2 where datediff(d, tb1.txdate, tb2.txdate) = -1 and tb1.class = tb2.class and tb1.code = tb2.code ) ) as a inner join ( --Find maximum island select code , class , txdate , row_number() over (order by code, class, txdate) as n from #items tb1 where not exists ( select * from #items tb2 where datediff(d, tb1.txdate, tb2.txdate) = 1 and tb1.class = tb2.class and tb1.code = tb2.code ) ) as b on an = bn
The only caveat in this approach is that the number of records in the minimum set should match the number of records in the maximum set. Until now, I could not do anything to make it untrue. However, I have not tested null values ββor performance.
source share