I'm trying to group patient readmissions that occur within separate 30 day windows (SQL Server 2008). After multiple attempts at recursive CTE's, I'm just going in circles. All help is greatly appreciated.
Problem:
If a patient is admitted within 30 days of the first discharge, count all those admissions in the first period (in the example below, the second admit date of 7/7/2011 is within the 7/20/2011 window).
The first admit immediately after the above 30 day period should be treated as a new 30 day window and any admits within 30 days of its discharge become part of group 2, etc.
So, record 3 is the start of a new 30 day window, even though this admit is within 30 days of the discharge of the prior record (admit on 8/5/2011 is before 8/26/2011, but 8/5/2011 is greater than the 7/20/2011 terminus that started the first 30 day window).
Record 4 was admitted prior to 8/31/2011, therefore it should be included in group 2.
Record 5 stands alone because it was admitted more than 30 days after the 8/31/2011 date that ended group 2.
The desired output for the example recordset is the sum of charges for each 30 day start point.
Desired result:
MRN Admit TotalCharge 555 6/14/2011 $25 555 7/30/2011 $39 555 11/3/2011 $10
Example recordset:
Acct MRN Admit Disc Disch+30 Charge 590 555 6/14/2011 6/20/2011 7/20/2011 15 938 555 7/7/2011 7/27/2011 8/26/2011 10 1011 555 7/30/2011 8/1/2011 8/31/2011 9 1089 555 8/5/2011 9/14/2011 10/14/2011 30 3011 555 11/3/2011 11/23/2011 12/23/2011 10