SQL分组查询中子查询错误导致新患者统计值异常求助
问题分析与解决方案
错误原因
- 子查询未关联外层的
practice字段,导致它计算的是全表所有新患者的总数,而非对应诊所的新患者数 - 子查询没有添加
ServiceDate时间过滤,统计范围是整个表的历史数据,不是你指定的2022年10月
修正方案
方案1:关联子查询(贴合你原有逻辑)
给子查询加上与外层practice的关联条件,同时补充时间过滤:
select practice, count(distinct appointment_id) as 总患者数, (select count(distinct appointment_id) from Appointments as inner_a where inner_a.practice = outer_a.practice and inner_a.Patient_Status = 'New Patient' and inner_a.ServiceDate between '2022-10-01' and '2022-10-31') as 新患者数 from Appointments as outer_a where ServiceDate between '2022-10-01' and '2022-10-31' group by practice
方案2:条件聚合(更高效,推荐)
用CASE WHEN在聚合函数内直接统计符合条件的新患者,避免子查询带来的性能开销:
select practice, count(distinct appointment_id) as 总患者数, count(distinct case when Patient_Status = 'New Patient' then appointment_id end) as 新患者数 from Appointments where ServiceDate between '2022-10-01' and '2022-10-31' group by practice
扩展说明
后续添加其他指标时,可直接基于方案2的模式扩展,比如统计复诊患者数:
count(distinct case when Patient_Status = 'Returning Patient' then appointment_id end) as 复诊患者数
内容的提问来源于stack exchange,提问作者sqlrobert
相关产品推荐
相关产品推荐

