首页 > 解决方案 > SQL:如何将日期范围计数作为行而不是列?

问题描述

我的通用用例是获取一个或多个表中多个日期范围的记录计数。

我的具体用例是这样的:对于患者就诊表 (enc) 和妊娠表 (preg),获取预期截止日期前 9 个月、12 个月前、15 个月前等看到的患者数量。

我可以通过使用限制时间限制的 where 子句对遇到的表进行外部联接来获取所需的数据。但是,这似乎效率低下,打字很多,并且数据不是我想要的形式(我希望每个时间窗口都是一行而不是一列)。

以下是我目前的查询。如何重写它以获取数据行而不是列?

select 
  preg.org, 
  count(distinct nine.patient_id) `Pre-Delivery Visits (09 Months)`,
  count(distinct twelve.patient_id) `Pre-Delivery Visits (12 Months)`,
  count(distinct all.patient_id) `Pre-Delivery Visits (All)`,
  count(distinct preg.patient_id) `All Pregnancies`
from 
  pregnancy preg
  left outer join enc nine on preg.patient_id = nine.patient_id and nine.encounter_date < preg.est_delivery_date and nine.encounter_date > date_add(preg.est_delivery_date, (-30*9))
  left outer join enc twelve on preg.patient_id = twelve.patient_id and twelve.encounter_date < preg.est_delivery_date and twelve.encounter_date > date_add(preg.est_delivery_date, (-30*12))
  left outer join enc all on preg.patient_id = all.patient_id and all.encounter_date < preg.est_delivery_date
group by 1
;

数据以这种格式返回:

org    (09 Months)  (12 months)  (All)  (All Pregnancies)
org x  1            10           15     20            
org y  2            22           23     24
org z  200          202          230    250

我想得到这样的数据

org    time_box  count
org x  09 mon    1
org y  09 mon    2
org z  09 mon    202
org x  12 mon    10
...
etc.  

标签: sql

解决方案


我不确定这是否符合您的要求。这会计算不重叠的组,因此 12 个月实际上是 9-12 个月:

select (case when e.encounter_date > p.est_delivery_date - 30*9 day
             then 'nine'
             when e.encounter_date > p.est_delivery_date - 30*12 day
             then 'twelve'
             when e.encounter_date is not null
             then 'all pre-delivery'
             else 'all pregnancy'
        end) as grp,
       count(distinct p.patient_id)            
from pregnancy p left join
     enc e
     on e.patient_id = p.patient_id and
        e.encounter_date < p.est_delivery_date 
group by grp;

推荐阅读