查询有一些记录但没有其他记录的案例 - SQL Server 2008

Querying cases that have some records and not others - SQL Server 2008

我正在努力研究如何查询 table 个患者 ID 和诊断以及 return 个有一些诊断但没有其他诊断的病例。我一直在玩自连接,但似乎无法 'get it'。对这个(看似!)简单概念的任何帮助表示赞赏......我在这里找不到这个问题的先前答案。

用例:我需要 return 以下具有 'No Diagnosis' 或 'Basal Cell' 的患者 ID 列表作为诊断 AND他们的 IDS 没有任何其他行,其中 Cancer = 'Yes'

来源table

[PatientID]     [Diagnosis]       Cancer
1                No Diagnosis     No
1                Basal Cell       No
2                No Diagnosis     No
2                Basal Cell       No            
2                Colon            Yes
3                Breast           Yes
4                Basal Cell       No
5                No Diagnosis     No

在上面的列表中,PatientIDs 1、4 和 5 应该被 return 编辑,因为这些患者的行有 'No Diagnosis' 或 'Basal Cell' 而没有其他行癌症 = 'Yes'。 PatientID 2 被排除在外,因为他们也有 'Colon' 诊断,而 3 因为他们有 'Breast' 作为诊断。

希望这是有道理的并且你能提供帮助。非常感谢。

您可以使用 NOT EXISTS:

SELECT [PatientID], [Diagnosis], Cancer
FROM Patients AS p
WHERE [Diagnosis] IN ( 'No Diagnosis', 'Basal Cell') AND
      NOT EXISTS (SELECT 1 
                  FROM Patients  
                  WHERE [PatientID] = p.[PatientID] AND Cancer = 'Yes')

以下替代方案可能看起来更冗长,但可能更有效,因为它不使用 相关子查询 ,如上面的查询 NOT EXISTS做:

SELECT p1.[PatientID], [Diagnosis], Cancer
FROM #Patients AS p1
LEFT JOIN ( 
   SELECT DISTINCT [PatientID]
   FROM #Patients AS p
   WHERE [Diagnosis] NOT IN ( 'No Diagnosis', 'Basal Cell') AND Cancer = 'Yes'
) AS p2 ON p1.PatientID = p2.PatientID
WHERE [Diagnosis] IN ( 'No Diagnosis', 'Basal Cell') AND p2.PatientID IS NULL

请注意,如果这两种诊断都与癌症无关,则派生的第一个谓词 table,即 [Diagnosis] NOT IN ( 'No Diagnosis', 'Basal Cell') 可能不是必需的。

试试这个查询:

SELECT ...
FROM dbo.MyTable x
WHERE x.[Diagnosis] IN ('No Diagnosis', 'Basal Cell')
-- AND x.Cancer = 'No' -- I'm not sure from your question if it's needed 
AND NOT EXISTS (
    SELECT * 
    FROM dbo.MyTable y
    WHERE y.PacientID = x.PacientID
    AND x.[Diagnosis] NOT IN ('No Diagnosis', 'Basal Cell') -- I assume that Diagnosis columns is mandatory / NOT NULL
    AND x.Cancer = 'Yes'
)