2015-02-05 60 views
1

下面的代碼拋出一個錯誤:如何檢查列值的組合在SQL Server表

select * 
from inPersonMedChangeNotes as IP 
where 
    (IP.[Date], IP.Patient) not in (select EncounterDate, Patient 
            from tbl_patients_clinic_visit_records as VC 
            join tbl_patients as PS on VC.PatientId = PS.PatientId_this) 

錯誤:

non boolean expression where condition is expected

我試圖找到inPersonMedChangeNotes所有條目值的組合不在tbl_patients_clinic_visit_records表中。我該怎麼做呢?

+0

你不能爲你的'不in'子句中使用多列... – SoulTrain 2015-02-05 16:55:43

回答

1

您可以用左這樣做加盟:

SELECT * 
FROM inPersonMedChangeNotes as IP 
LEFT JOIN tbl_patients_clinic_visit_records as VC ON IP.[Date] = VC.EncounterDate AND IP.Patient = VC.Patient 
left join tbl_patients as PS on VC.PatientId = PS.PatientId_this 
WHERE VC.EncounterDate IS NULL 
+0

除了你可能會希望限制選擇IP *匹配的期望輸出要求 – randcd 2015-02-05 16:48:47

+0

這裏是我最終使用:SELECT * FROM 作爲inPersonMedChangeNotes IP LEFT JOIN tbl_patients_clinic_visit_records作爲VC對IP [日期] = VC.EncounterDate 左加入tbl_patients爲PS上VC.PatientId = PS.PatientId_this和IP。 Patient = PS.Name WHERE PatientClinicVisitRecords Id_this爲空 和PatientId_this爲空 – pQuestions123 2015-02-05 17:03:08

1

按照您的查詢的相同的結構,你可以使用not exists

select * 
from inPersonMedChangeNotes IP 
where not exists (select 1 
        from tbl_patients_clinic_visit_records 
        where ip.patient = vc.patientid and 
         ip.[date] = vc.encounterdate 
       ); 

我不認爲需要在patient表爲查詢。

+0

患者表是需要的,因爲ip.patient是一個字符串,vc.patientid是一個int – pQuestions123 2015-02-05 17:04:39

0

您需要使用LEFT OUTER JOIN。在你的情況下(未經測試):

select * 
from inPersonMedChangeNotes as IP 
LEFT JOIN (
      select EncounterDate, Patient 
      from tbl_patients_clinic_visit_records as VC 
      inner join tbl_patients as PS on VC.PatientId = PS.PatientId_this 
) V ON V.EncounterDate = IP.[Date] and IP.Patient = V.Patient 
where v.EncounterDate IS NULL 
0

NOT IN查詢可以只檢查一個字段,它不能同時檢查多個字段。檢查單獨的NOT IN子句中的每個條件,並在它們之間使用AND。是這樣的:

select * 
from inPersonMedChangeNotes as IP 
where 
    IP.[Date] not in (select EncounterDate 
            from tbl_patients_clinic_visit_records as VC 
            join tbl_patients as PS on VC.PatientId = PS.PatientId_this) 

And 


    IP.Patient not in (select Patient 
            from tbl_patients_clinic_visit_records as VD 
            join tbl_patients as PQ on VD.PatientId = PQ.PatientId_this) 
+1

我不認爲這會完成我正在努力完成的任務 – pQuestions123 2015-02-05 17:02:30

0

First create function that will return EncounterDate, Patient then use outer apply. (if it works -:) ) it will give you best performance.

CREATE function spn() 
RETURNS TABLE 
AS 
RETURN 
    (select EncounterDate, Patient 
      from tbl_patients_clinic_visit_records as VC 
      join tbl_patients as PS on VC.PatientId = PS.PatientId_this) 
     GO 

    select * 
    from inPersonMedChangeNotes as IP 
    OUTER APPLY dbo.spn() 
+0

您還可以在數據庫上創建觸發器用於alter table來跟蹤任何列的更改 – 2015-02-05 18:53:32