sql - 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.
解决方案
我不确定这是否符合您的要求。这会计算不重叠的组,因此 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;
推荐阅读
- reactjs - 带有事件的 Swiperjs 反应
- php - Laravel 的内置 Auth 功能在使用带有前缀 url 的本地化时会导致错误
- python - 安装 anaconda 后,无法导入新的 pip 安装模块
- python - Python将不相等的数据帧与真/假文本进行比较以获取列输出
- python - 如何处理字符串列表,其中每个字符串也可能是逗号分隔的字符串列表?
- javascript - 奇怪的重新选择选择器行为
- jmeter - 在 JMeter 的 HTTP 采样器中遍历每一行并访问每一列
- javascript - 将基于 ES6 钩子的应用程序转换为基于类的组件
- android - Volley NetworkResponse 中的重复数据
- jmeter - 如何在性能测试期间在 jmeter 中执行并发 10000K 线程?