t-sqlnotinexistential-operator

TSQL IN and NOT IN


I have the below query that returns all diagnosis that do not have a '-829' value associated to them. The query does work but I think that I've made it harder than it should be. Is there a tidier way of doing this?

select distinct
c2.diagnosisn DiagnosisName, 
a2.text CareLookup
from core_patdiagnosis c1 
LEFT OUTER JOIN core_diagnosis c2 ON c1.diagnosis = c2.id 
LEFT OUTER JOIN core_carecontext c3 ON c1.carecontex = c3.id 
LEFT OUTER JOIN applookup_instance a1 ON c1.lkp_specialty = a1.id 
LEFT OUTER JOIN core_diagnosis_taxonomyma c5 ON c2.id = c5.id 
LEFT OUTER JOIN applookup_instance a3 ON c5.lkp_taxonomyna = a3.id 
LEFT OUTER JOIN applookup_instance a2 ON c3.lkp_context = a2.id

where c2.id IN
(
select c11.id core_diagnosis_c1_id
from core_diagnosis c11 
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id 
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE
c11.isactive = 1
and a11.id != -829 or a11.id is null
)

AND
c2.id NOT IN
(
select c12.id ProcID
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id 
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE
c12.isactive = 1
and a12.id = -829 or a12.id is null
)

AND
c1.sys_creation_datetime > '01 Dec 2017 00:00:00' AND a2.text like 
'%Emergency%'

Solution

  • extra stuff not used

    a2.text like '%Emergency%' breaks the outer join

    select distinct c2.diagnosisn DiagnosisName, a2.text CareLookup
    from core_patdiagnosis  c1 
    JOIN core_diagnosis     c2 ON c2.id = c1.diagnosis  
    JOIN core_carecontext   c3 ON c3.id = c1.carecontex 
    JOIN applookup_instance a2 ON a2.id = c3.lkp_context     
    
    where c2.id IN
    ( select c11.id 
      from core_diagnosis c11 
      LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id 
      LEFT OUTER JOIN applookup_instance a11        ON c21.lkp_taxonomyna = a11.id
      WHERE c11.isactive = 1 and a11.id != -829 
         or a11.id is null
    )
    
    AND
    c2.id NOT IN
    ( select c12.id 
      from core_procedure c12
      LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id 
      LEFT OUTER JOIN applookup_instance a12        ON c22.lkp_taxonomyna = a12.id
      WHERE c12.isactive = 1 and a12.id = -829 
         or a12.id is null
    )
    
    AND c1.sys_creation_datetime > '01 Dec 2017 00:00:00' 
    
    AND a2.text like '%Emergency%'