I used my own test data, this is a very complex material. The cursor may be easier to handle. But I'm not a big fan of cursors. I gave him the best shot:
declare @t table(record int, date datetime)
insert @t values(1,'19-Oct-2007'),
(2,'03-Dec-2007'),
(3,'2-may-2009'),
(4,'16-Oct-2009'),
(5,'26-Oct-2009'),
(6,'30-Oct-2009'),
(7,'01-Nov-2009'),
(8,'16-Nov-2009'),
(9,'30-Nov-2009'),
(10,'11-Dec-2009'),
(11,'11-Dec-2010'),
(12,'11-Dec-2010'),
(13,'11-Dec-2010')
;with a as
(
select datediff(day, t1.date, t2.date) daysapart,
row_number() over (order by count desc) rn,
b.count,
t1.record fromrecord,
t2.record torecord
from @t t1
join @t t2
on t1.date <= t2.date
and dateadd(month, 6, t1.date) > t2.date
and t1.record <= t2.record
cross apply (select count(*) count from @t where record between t1.record and t2.record) b
)
, b as
(
select * from a where not exists
(select 1 from a b where (a.fromrecord between b.fromrecord and b.torecord
or a.torecord between b.fromrecord and b.torecord)
and a.rn > b.rn and not exists(select 1 from a c where
(b.fromrecord between c.fromrecord and c.torecord
or b.torecord between c.fromrecord and c.torecord)
and b.rn > c.rn))
)
select count, fromrecord, torecord, daysapart from b
Result:
count fromrecord torecord daysapart
----------- ----------- ----------- -----------
7 4 10 56
3 11 13 0
2 1 2 45
1 3 3 0