如何根据入院和出院日期计算入住率

how to calculate occupancy on the basis of admission and discharge dates

假设我有耐心 admission/claim 明智的数据,如下例所示。 patient_id 和 hosp_id 列的数据类型是 VARCHAR

Table姓名claims

rec_no patient_id hosp_id admn_date discharge_date
1 1 1 01-01-2020 10-01-2020
2 2 1 2019-12-31 11-01-2020
3 1 1 11-01-2020 15-01-2020
4 3 1 04-01-2020 10-01-2020
5 1 2 16-01-2020 17-01-2020
6 4 2 01-01-2020 10-01-2020
7 5 2 02-01-2020 11-01-2020
8 6 2 03-01-2020 12-01-2020
9 7 2 04-01-2020 13-01-2020
10 2 1 2019-12-31 10-01-2020

我有另一个table,其中存储了医院的病床strength/max占用强度。

table姓名beds

hosp_id bed_strength
1 3
2 4

预期结果 我想找出任何一天超过其宣布的床强度的医院明智日期。

我试过的代码 没什么,因为我是新手 SQL。但是,我可以使用以下策略在 R 中解决这个问题

同时,我也想知道是否可以在 sql 中不进行旋转(如果有的话),因为在 claims table 中有 1500 万 + 行和旋转真的会减慢这个过程。请帮忙。

您可以使用 generate_series() 在 Postgres 中做一些非常相似的事情。按日期入住:

select c.hosp_id, gs.date, count(*) as occupanyc
from claims c cross join lateral
     generate_series(admn_date, discharge_date, interval '1 day') gs(date)
group by c.hosp_id, gs.date;

然后将其用作子查询以获取超过阈值的日期:

select hd.*, b.strength
from (select c.hosp_id, gs.date, count(*) as occupancy
      from claims c cross join lateral
           generate_series(c.admn_date, c.discharge_date, interval '1 day') gs(date)
      group by c.hosp_id, gs.date
     ) hd join
     beds b
     using (hosp_id)
where h.occupancy > b.strength