每日SQL练习 -- 24年阿里(医院门诊复诊率与抗生素用药占比统计)
这个题目算是我学SQL以来,遇到的比较难的题目了,很考察逻辑思维能力,lag()函数很久没用过有点忘记函数用法了,正好可以复习一下窗口函数
【背景】
某三甲医院每月复盘各科室(Department)的复诊与用药情况。请基于就诊记录与处方,统计每个科室在 2024 年 2 月的就诊概览,并衡量复诊率与抗生素用药占比,用于门诊管理优化。
【原始表】
- patients(患者)表
- patient_id INT 主键
- patient_name VARCHAR
- visits(就诊)表
- visit_id INT 主键
- patient_id INT 外键 → patients.patient_id
- dept VARCHAR 科室(如 Cardio/ENT)
- visit_date DATE 就诊日期
- diagnosis_code VARCHAR 诊断编码(本题不强制使用)
- prescriptions(处方)表
- prescription_id INT 主键
- visit_id INT 外键 → visits.visit_id
- drug_code VARCHAR
- drug_name VARCHAR
- is_antibiotic TINYINT(1) 是否抗生素(1 是,0 否)
【要求】
输出每个科室在 2024 年 2 月的指标,并按 dept 升序排序:
- dept:科室
- feb_2024_visits:2 月就诊人次
- feb_2024_unique_patients:2 月就诊去重人数
- feb_2024_revisit_rate:2 月复诊率 = 当月就诊人次中“距同患者同科室上一次就诊≤30天”的占比(%,保留两位小数)= 复诊人次 / 就诊人次
- feb_2024_antibiotic_rate:2 月抗生素用药占比 = 当月处方中抗生素条目数 / 全部处方条目数(%,保留两位小数;分母为 0 则 0.00)
说明:
- 复诊判断使用同患者同科室的上一次就诊日期(可发生在 2 月之前),若 DATEDIFF(curr, prev) ≤ 30,则当前这次计为“复诊”。
- 占比类均四舍五入保留两位小数。
【题解】
selecttable1.dept,table1.feb_2024_visits,table1.feb_2024_unique_patients,table2.feb_2024_revisit_rate,table1.feb_2024_antibiotic_rate
from(selectt1.dept,count(distinct t1.visit_id) feb_2024_visits,count(distinct t1.patient_id) feb_2024_unique_patients,if(count(t2.prescription_id) = 0,'0.00',round(sum(t2.is_antibiotic) * 100 / count(t2.prescription_id),2)) feb_2024_antibiotic_ratefromvisits t1left join prescriptions t2on t1.visit_id = t2.visit_idwhereyear(t1.visit_date) = 2024and month(t1.visit_date) = 2group byt1.dept) table1left join (selectdept,round(sum(casewhen datediff(curr, prev) <= 30and prev is not null then 1else 0end) * 100 / count(visit_id),2) feb_2024_revisit_ratefrom(selectdept,visit_date curr,visit_id,patient_id,lag(visit_date, 1, 0) over (partition bypatient_id,deptorder byvisit_date) as prevfromvisits) uwhereyear(curr) = 2024and month(curr) = 2group bydept) table2
on table1.dept = table2.dept
