2012-06-21 63 views
0

enter image description hereWHERE NOT EXISTS不工作SQL Server 2008的

這是this一個相關的問題,但與EXISTS代替

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' 
) 

此查詢工作正常,但是當我嘗試添加另一場選擇表達式我必須使用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' 
) 

回答

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' 
+0

返回沒有結果以及 – wootscootinboogie

+0

你能用句子描述你究竟想要什麼查詢嗎?看起來您正試圖返回PatientId和ICD號碼,其中ICD描述爲'N'%TextOfNote%'且ICD號碼不是N'25000'?是對的嗎? –

+0

這是正確的。 – wootscootinboogie

0

你有兩個病人,patientICD,tblICD在這裏發揮作用一個在主查詢中,另一個在「不存在」。嘗試使用表別名。

SELECT X FROM TABLEA A 
INNER JOIN TABLEB B 
    ON A.ID = B.ID 

你必須引用「不存在」 ...抓緊到「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') 
)