我一直在纠结于如何查询一个病人ID和诊断表,并返回有一些诊断但没有其他诊断的病例。我一直在玩自我加入,但似乎不能“理解”。在这个问题上,任何帮助都会得到赞赏(看起来!)简单的概念..。我在这里找不到这个问题的先前答案。
用例:我需要返回下面的病人IDs列表,他们要么有“无诊断”,要么有“Basal Cell”作为诊断,并且在他们的IDS中没有任何其他行,巨蟹座=‘是’
源表
[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在上面的列表中,应该返回PatientID 1、4和5,因为这些患者有“无诊断”或“基础细胞”的行,也没有癌症=“是”的其他行。PatientID 2被排除在外,因为他们也有‘结肠’诊断,因为他们有‘乳房’作为诊断。
希望这是有意义的,你也能帮上忙。非常感谢。
发布于 2015-03-03 21:25:13
您可以使用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请注意,如果这两种诊断都与癌症无关,则派生表的第一个谓词,即[Diagnosis] NOT IN ( 'No Diagnosis', 'Basal Cell'),可能是不必要的。
发布于 2015-03-03 21:28:32
请尝试以下查询:
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'
)https://stackoverflow.com/questions/28842099
复制相似问题