如何在sql server表中检查列值的组合

时间:2015-02-05 16:43:00

标签: sql 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)

错误:

  

非布尔表达式,其中包含条件

我正在尝试查找inPersonMedChangeNotes中的所有条目,其中值的组合不在tbl_patients_clinic_visit_records表中。我该怎么做?

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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表。

答案 2 :(得分: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

答案 3 :(得分: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)

答案 4 :(得分:0)

  

首先创建将返回EncounterDate的函数,然后是Patient   使用外部申请。 (如果它有效 - :))它会给你最好的   性能

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