/*
drop table #t
create table #t (id int, FirstDateOfService datetime, LastDateOfService datetime, PerformingProvider varchar(30));
go
insert into #t (id, FirstDateOfService, LastDateOfService, PerformingProvider)
values
(2202 , '2012-09-18' , '2012-09-21' , 'St. Luke''s')
,(2202 , '2012-09-29' , '2012-10-04', 'St. Luke''s')
,(4280 , '2012-09-19' , '2012-09-20', 'Seton')
,(4280 , '2012-09-19' , '2012-10-18', 'Seton')
,(4280 , '2012-09-21' , '2012-10-09', 'Seton')
,(4280 , '2012-10-10' , '2012-10-17', 'Seton')
,(8980 , '2013-06-20' , '2013-06-24', 'Denton Regional')
,(8980 , '2013-07-06' , '2013-07-06' , 'Denton Regional')
*/
;with cte (rid, id, FirstDateOfService, LastDateOfService, PerformingProvider)
as (
select rid=row_number() over (PARTITION BY id order by FirstDateOfService),*
from #t
)
select t1.id, t1.PerformingProvider, Readmission=count(*)
from cte t1
inner join cte t2
on t1.id = t2.id
and t1.rid = t2.rid-1
and t2.FirstDateOfService < dateadd(day, 30, t1.LastDateOfService)
and t1.PerformingProvider = t2.PerformingProvider
group by t1.id, t1.PerformingProvider
order by t1.id;
ただし、データをクレンジングする必要があると思います。id=4280 に 2 つの同じ firstdayofservice (2012-09-19) があるのに lastdayofservice が異なるのはなぜですか?