近日接到同事项目上统计需求,需要统计便秘患者。规则是连续三天(包含三天)以上大便次数为零的患者。统计思路使用用户连续登录3天一样,用记录日期减去排序号,所得日期相同;再统计日期相同的记录大于等于3即可。
示例数据
因表中有多个患者的体征信息,需要通过partition by给每个患者的记录重建排序号。
select to_char(record_date - nums, 'yyyy-mm-dd') record_date,
patient_id,
visit_id
from (SELECT t.record_date,
row_number() over(partition by t.patient_id, t.visit_id order by t.record_date) nums,
t.vital_value,
t.patient_id,
t.visit_id
FROM nurse_vital_signs_rec t
where t.vital_signs = '大便次数'
and t.vital_value = '0'
order by t.patient_id, t.visit_id, t.record_date)
查出数据
再统计数量大于等于3的记录
select record_date, patient_id, visit_id
from (select to_char(record_date - nums, 'yyyy-mm-dd') record_date,
patient_id,
visit_id
from (SELECT t.record_date,
row_number() over(partition by t.patient_id, t.visit_id order by t.record_date) nums,
t.vital_value,
t.patient_id,
t.visit_id
FROM nurse_vital_signs_rec t
where t.vital_signs = '大便次数'
and t.vital_value = '0'
order by t.patient_id, t.visit_id, t.record_date))
group by record_date, patient_id, visit_id
having count(record_date) >= 3;