这是this的相关问题,但使用EXISTS代替IN
SELECT distinct Patient.patientid
FROM Patient P
JOIN patientICD pICD
ON P.patientid = pICD.patientid
AND P.admissiondate = pICD.admissiondate
AND P.dischargedate = pICD.dischargedate
JOIN tblICD
ON pICD.primarycode = tblICD.ICD_ID
WHERE tblICD.descrip LIKE N'%diabetes%'
AND patient.patientID not in (
SELECT distinct Patient.patientid
FROM Patient P
JOIN patientICD pICD
ON P.patientid = pICD.patientid
AND P.admissiondate = pICD.admissiondate
AND P.dischargedate = pICD.dischargedate
JOIN tblICD ON pICD.primarycode = tblICD.ICD_ID
WHERE tblICD.icd_id =N'25000'
)
此查询工作正常,但是当我尝试向select表达式添加另一个字段时,我必须使用WHERE EXISTS
并且以下查询返回0结果,而上面的查询返回130.我正在尝试添加从第一个查询到结果集的tblicd.icd_id字段,我做错了。
SELECT DISTINCT Patient.patientid, tblicd.icd_id
FROM Patient
INNER JOIN patientICD
ON Patient.patientid = patientICD.patientid
AND Patient.admissiondate = patientICD.admissiondate
AND Patient.dischargedate = patientICD.dischargedate
INNER JOIN tblICD
ON patientICD.primarycode = tblICD.ICD_ID
WHERE tblICD.descrip LIKE N'%TextOfNote%'
and not exists (
SELECT DISTINCT Patient.patientid, tblicd.icd_id
FROM Patient
INNER JOIN patientICD
ON Patient.patientid = patientICD.patientid
AND Patient.admissiondate = patientICD.admissiondate
AND Patient.dischargedate = patientICD.dischargedate
INNER JOIN tblICD
ON patientICD.primarycode = tblICD.ICD_ID
WHERE tblICD.icd_id = N'25000'
)
答案 0 :(得分:1)
我没有针对您的架构运行此操作,但请尝试一下
修改... 强>
SELECT DISTINCT Patient.patientid, tblicd.icd_id
FROM Patient
INNER JOIN patientICD
ON Patient.patientid = patientICD.patientid
AND Patient.admissiondate = patientICD.admissiondate
AND Patient.dischargedate = patientICD.dischargedate
INNER JOIN tblICD
ON patientICD.primarycode = tblICD.ICD_ID
WHERE tblICD.descrip LIKE N'%TextOfNote%'
AND tblICD.icd_id <> N'25000'
答案 1 :(得分:0)
你有两个患者,患者ICD,tblICD在这里发挥作用..一个在主查询中,另一个在“不存在”中。尝试使用表别名。
SELECT X FROM TABLEA A
INNER JOIN TABLEB B
ON A.ID = B.ID
你必须在“not exists”中引用主查询...密切关注“ON”连接条件和where子句。
WHERE (tblICD.descrip LIKE N'%TextOfNote%') and not exists
(
SELECT DISTINCT Patient.patientid, tblicd.icd_id
FROM Patient INNER JOIN
patientICD ON Patient.patientid = patientICD.patientid AND Patient.admissiondate = patientICD.admissiondate AND
Patient.dischargedate = patientICD.dischargedate INNER JOIN
tblICD ON patientICD.primarycode = tblICD.ICD_ID
WHERE (tblICD.icd_id = N'25000')
)