选择与一个列值关联但不与另一个列值关联的客户

Selecting clients who have an association with one column value, but not another

我正在尝试制作一份报告,列出活跃客户 (case_status = 'A'),他们附有旧版本的文档,但没有新版本,但我们的数据库是这样的布局所有文件都列在一个 table 中,因此一些客户会附有十几个不同的文件。其中一些是重复文件。

例如

patient_id     Doc_code
p01            doc1
p01            doc2
p01            doc3
po1            doc4
p02            doc2
po2            doc3

我需要知道谁的 doc_code 为 'DIAGDOC' 而没有 doc_code 的 'DIAGDOC5',因此我们知道谁需要更新。

select 

de.patient_id,
de.episode_id

from doc_entity de
join patient p
on p.patient_id = de.patient_id and p.episode_id = de.episode_id
where p.case_status = 'A' 

group by de.patient_id, de.episode_id, de.doc_code
having (de.doc_code in ('DIAGDOC'))and (de.doc_code not in ('DIAGDOC5'))
order by de.patient_id, de.episode_id 

except 子句有效吗?

select
de.patient_id,
de.episode_id

from doc_entity de
join patient p
on p.patient_id = de.patient_id and p.episode_id = de.episode_id
where p.case_status = 'A' 
and de.doc_code = 'DIAGDOC'

EXCEPT

select 

de.patient_id,
de.episode_id

from doc_entity de
join patient p
on p.patient_id = de.patient_id and p.episode_id = de.episode_id
where p.case_status = 'A' 
and de.doc_code = 'DIAGDOC5'*

顶部块 returns 所有带有 diagdoc 的行和 except 块删除所有带有 diagdoc5 的行,只留下那些带有过时文档的行

以下是否有效 -

select 
    aa.patient_id, aa.episode_id 
from 
(
    select  
            de.patient_id
        ,   de.episode_id
        ,   MAX(case doc_code WHEN 'DIAGDOC'  THEN 'YES'  ELSE 'NO' end) as 'DIAGDOCExists'
        ,   MAX(case doc_code WHEN 'DIAGDOC5' THEN 'YES'  ELSE 'NO' end) as 'DIAGDOC5Exists'
    from 
        doc_entity de join patient p on p.patient_id = de.patient_id and p.episode_id = de.episode_id
    where 
        p.case_status = 'A' 
    group by 
        de.patient_id, de.episode_id
) as aa where aa.DIAGDOCExists = 'YES' and aa.DIAGDOC5Exists = 'NO'