sql - 如何获取每个类别中存在但其他类别中不存在的项目的计数?
问题描述
我有一张到医院的不同 visit_types 的桌子。他们是Inpatient
,,,Outpatient
Emergency
我想知道仅存在于 eachvisit_type
而不是 other的主题的数量visit_types
。在上面的例子中
住院人数 - 4
门诊人数 -2
紧急计数 - 3
我尝试了以下但不确定它是否准确?
SELECT count(DISTINCT PERSON_ID) FROM Visit WHERE PERSON_ID NOT IN
(select distinct person_id from Visit where visit_type = 'Inpatient')
AND VISIT_type = 'Outpatient';
SELECT count(DISTINCT PERSON_ID) FROM Visit WHERE PERSON_ID NOT IN
(select distinct person_id from Visit where visit_type = 'Inpatient')
AND VISIT_type = 'Emergency';
当我这样做时,它包括和之间的共同Emergency
主题Outpatient
?
我怎样才能正确获得计数?
解决方案
我想知道仅存在于每个类别下但不存在于其他类别中的科目数量。
您可以按患者汇总,跟踪类别。然后再次聚合:
select visit_type, count(*)
from (select patientId, min(visit_type) as visit_type
from t
group by patientId
having min(visit_type) = max(visit_type)
) p
group by visit_type;
另一种方法group by
在聚合之前使用 but 过滤器:
select visit_type, count(*)
from t
where not exists (select 1
from t t2
where t2.patientid = t.patientid and
t2.visit_type <> t.visit_type
)
group by visit_type;
注意:在这种情况下,count(*)
是对行进行计数。如果您的数据有重复,请使用count(distinct visit_type)
.
我不知道“我将住院患者类别视为基本类别”应该是什么意思,但问题本身很清楚。
编辑:
我不清楚您想要的不同类别之间的关系。您可能会发现使用起来最灵活:
select visit_type, count(*)
from (select patientId,
bool_or(visit_type = 'Inpatient') as has_inpatient,
bool_or(visit_type = 'Outpatient') as has_oupatient,
bool_or(visit_type = 'Emergency') as has_emergency,
count(distinct visit_type) as num_visit_types
from t
group by patientId
) p
where num_visit_types = 1
group by visit_type;
此版本与前面的两个查询相同。但是您可以使用这些has_
标志进行额外的过滤——例如where num_visit_types = 1 or (num_visit_types = 2 and has_inpatient)
,如果您想要一种类型的人或一种类型加上“住院病人”。
推荐阅读
- json - SQL Server 插入带有其他外部参数的 JSON 数据
- javascript - 在 HTML 中切换图像隐藏/可见
- android-studio - 如何配置 Android Studio 以识别带有 SystemApi 注释的方法
- javascript - 物化日期选择器仅在单击完成按钮时更新
- omnet++ - 构建venes_inet 失败
- java - 从 Java 中的字符串中过滤非 MySQL Latin1 字符
- sql - 包含重复项的多个字符串
- kubernetes - Apache Camel 与 Kubernetes
- python - Python按最后一个字母和扩展名选择文件
- php - 多个 PHP 标记中的一个 PHP 变量