What you seem to be looking for are sequences of consecutive days. Assuming you are using SQL Server 2005 or later, you can use the following approach. For each patient, retrieve only days in a sequence. Then list the days. The difference between them will be constant for the "treatment".
Here is an example:
select patientId, seqStartDate, count(*) as NumDays, sum(NumOnDay) as NumRecs, dateadd(day, count(*) - 1, seqStartDate) as SeqEndDate from (select dp.*, row_number() over (partition by patientId order by StartDate) as seqnum, dateadd(day, - row_number() over (partition by patientId order by StartDate) StartDate ) as seqStartDate from (select cast(StartDate as date) as thedate, patientId, count(*) as NumOnDay from table group by cast(StartDate as date), patientId ) dp ) dp group by patientId, seqStartDate order by 1, 2
Actually, this syntax also uses cast(<val> as date) , which is the syntax of SQL Server 2008 to remove the time component. Alternative methods exist if you are using SQL Server 2005.
Gordon linoff
source share