SQL: Gaps and Islands, Grouped dates

后端 未结 1 674
旧时难觅i
旧时难觅i 2021-01-18 16:33

I am trying to group dates within 3 days of each other and assign points based on readmission\'s within 30 days. A MRN would receive 3 points per readmission. Any help on mo

相关标签:
1条回答
  • 2021-01-18 17:29

    This answer works for the example you provided. It might be useful if you have small tables and limited admission. (It use recursion on the dates).

    WITH a AS (
        SELECT
            z1.VisitDate
            , z1.OrganizationMrn
            , (SELECT MIN(VisitDate) FROM #z WHERE VisitDate > DATEADD(day, 3, z1.VisitDate)) AS NextDay
        FROM
            #z z1
        WHERE
            CATEGORY = 'Inpatient'
    ), a1 AS ( 
        SELECT
            OrganizationMrn
            , MIN(VisitDate) AS VisitDate
            , MIN(NextDay) AS NextDay
        FROM
            a
        GROUP BY
            OrganizationMrn
    ), b AS (
        SELECT
            VisitDate
            , OrganizationMrn
            , NextDay
            , 1 AS OrderRow
        FROM
            a1
    
    
        UNION ALL
    
        SELECT
            a.VisitDate
            , a.OrganizationMrn
            , a.NextDay
            , b.OrderRow +1 AS OrderRow
        FROM
            a
            JOIN b
            ON a.VisitDate = b.NextDay
    ), c AS (
    SELECT
        VisitDate
        , (SELECT MAX(VisitDate) FROM b WHERE b1.VisitDate > VisitDate) AS PreviousVisitDate
    FROM
        b b1
    )
    SELECT
        c1.VisitDate
        , CASE 
            WHEN DATEDIFF(day,c1.PreviousVisitDate,c1.VisitDate) < 30 THEN PreviousVisitDate
            ELSE NULL
         END AS ReAdmissionFrom
        , CASE
            WHEN DATEDIFF(day,c1.PreviousVisitDate,c1.VisitDate) < 30 THEN 3
            ELSE 0
        END AS Points
    FROM
        c c1
    
    0 讨论(0)
提交回复
热议问题