两个类似的SQL Server问题:
db_members是一个由patient_id, provider_id和level_of_care_id分类的成员级表。
目的是将患者从不同的聚集水平中拉出来。
在第一个查询中,我们希望从这6个级别的护理中提取所有患者,但对于LOC 100.007,我们需要从一个provider_id('119282 ')中排除患者;
在第二个查询中,我们希望从这6个级别的护理中提取所有患者,但对于LOC 100.007,我们只需要包括provider_id ('119282 ') patients;
(这是查询的简化版本)
select patient_id, provider_id, level_of_care_cd,
from db_members
where level_of_care_cd in ('100.001', '100.004', '100.007', '100.022', '100.034', '100.037')
group by level_of_care_cd, provider_id
排除只有一个LOC的提供商
where level_of_care_cd in ( <full list> )
and not (level_of_care_cd = '100.007' and provider_id = '119282')
只要不使用空值,这是等价的:
where level_of_care_cd in ( <full list> )
and (level_of_care_cd <> '100.007' or provider_id <> '119282')
允许一个提供者使用一个LOC
注意空值:
where level_of_care_cd in ( <full list> )
and not (level_of_care_cd = '100.007' and provider_id <> '119282')
where level_of_care_cd in ( <full list> )
and (level_of_care_cd <> '100.007' or provider_id = '119282')
等价是德摩根定律的结果。使用not
的表单可能最自然地符合人们的思维方式。请记住,or
的优先级低于and
,因此括号很重要。
试试这个
select case when level_of_care_cd ='100.007' and
patient_id not in (Select patient_id from patients where
provider_id='119282')
then patient_id end as patient_id
, provider_id,
level_of_care_cd,
from db_members
where level_of_care_cd in ('100.001', '100.004', '100.022', '
'100.007`, 100.034', '100.037')
group by level_of_care_cd, provider_id