首页 > 解决方案 > 如何获取每个类别中存在但其他类别中不存在的项目的计数?

问题描述

我有一张到医院的不同 visit_types 的桌子。他们是Inpatient,,,OutpatientEmergency

在此处输入图像描述

我想知道仅存在于 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

我怎样才能正确获得计数?

标签: sqlpostgresql

解决方案


我想知道仅存在于每个类别下但不存在于其他类别中的科目数量。

您可以按患者汇总,跟踪类别。然后再次聚合:

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),如果您想要一种类型的人或一种类型加上“住院病人”。


推荐阅读