0

我有一个带有示例数据的表“访问”:

患者 ID | date_admitted | 出院日期 |

971 |2011-03-25 | 2011-03-25|

971 |2011-08-08 |2011-08-08 |

971 |2011-08-25 |2011-08-25 |

971 |2011-09-03 |2011-09-03 |

971 |2011-10-03 |2011-10-09 |

我正在尝试根据两种情况计算患者的再入院次数

1) 在 0 到 30 天内。

2) 在 31 至 90 天内。

期望的结果:

患者 ID | readmission_count_30| readmission_count_90|

971 | 2 | 1 |

Readmission_count_30 :“2”,因为数据中存在两个录取日期,从录取日期 2011-08-08 开始,到 2011-09-08 结束

Readmission_count_90 :“1”,因为从录取日期 2011-08-08 开始的数据中存在一个录取日期,并且在日期范围 2011-08-08 + 间隔“31 天”和 2011-08-08 内存在一个录取日期+ 间隔“90 天”

我试图获得 readmission_count_30 但逻辑有缺陷。

    select admit.patient_id,count(*)
    from visits admit 
    left outer join (select r1.patient_id, r1.date_admitted, r1.date_discharged,
    r2.id as readmit_type 
    from visits r1) readmit 
    on admit.patient_id = readmit.patient_id and 
    admit.date_admitted < readmit.date_admitted and readmit.date_admitted between admit.date_admitted AND           
    admit.date_admitted + INTERVAL '30 days' 
    group by admit.patient_id 
4

1 回答 1

0

SQL小提琴

select
    patient_id,
    count(
        date_admitted > '2011-08-08'
        and date_admitted <= '2011-08-08'::date + interval '30 days'
        or null
    ) as readmission_count_30,
    count(
        date_admitted > '2011-08-08'::date + interval '30 days'
        and date_admitted <= '2011-08-08'::date + interval '90 days'
        or null
    ) as readmission_count_90
from visits
group by patient_id

通用版

select
    patient_id,
    count(
        date_admitted > first_admitted
        and date_admitted <= first_admitted + interval '30 days'
        or null
    ) as readmission_count_30,
    count(
        date_admitted > first_admitted + interval '30 days'
        and date_admitted <= first_admitted + interval '90 days'
        or null
    ) as readmission_count_90
from
    visits
    inner join
    (
        select patient_id, min(date_admitted) as first_admitted
        from visits
        group by patient_id
    ) f using (patient_id)
group by patient_id
于 2013-08-12T18:26:39.103 回答