Forum Discussion

thorrocks's avatar
thorrocks
Copper Contributor
Aug 16, 2024

Partition rows by id and DateColumn or DateColumn + 1

  Hello all. I'm trying to partition out data by patient stay and select the stay with the greatest discharge date. The only thing I'm struggling with is, multiple stays where the admit date is the ...
  • rodgerkong's avatar
    Aug 17, 2024

    thorrocks 

    What's the rule of a sequence of dates? For example:  'AdmitDate' contains ('2024-08-01', '2024-08-02', '2024-08-03'). Should they be treated as the same? In my understanding, it must be treated as one, or it will cause confusion.

    Base on this, it can be resolve by Recursive  CTE, Add a AdmitId to identify the rows 'treated one', then group by PatientId and AdmitId, using aggregate functions to get data you need. 

    WITH HT (PatientId, AdmitDate, AdmitId, DischargeDate, DaysToFollowUp)
    AS
    (
    	SELECT PatientId, AdmitDate, ROW_NUMBER() OVER (ORDER BY PatientId, AdmitDate), DischargeDate, DaysToFollowUp 
    	FROM #HospitalStays
    	WHERE DATEADD(day, 1, AdmitDate) NOT IN (SELECT AdmitDate FROM #HospitalStays)
    	UNION ALL
    	SELECT HT.PatientId, HS.AdmitDate, HT.AdmitId, HS.DischargeDate, HS.DaysToFollowUp
    	FROM #HospitalStays HS
    	INNER JOIN HT
    	ON 
    		HS.PatientId = HT.PatientId
    		AND DATEADD(day, 1, HS.AdmitDate) = HT.AdmitDate
    )
    SELECT PatientID, 
    MIN(AdmitDate) AS AdmintDate,   --OR use MAX to get max AdminDate of Dates treated as one
    MAX(DischargeDate) AS DischargeDate, 
    MAX(DaysToFollowUp) AS DaysToFollowUp  -- or use Min
    FROM HT
    GROUP BY PatientID, AdmitId

     

Resources