I have a population of patients in my main query (COPD) and another population of patients in my subquery (CANC). I want to exclude the CANC PAT_ID's from the main query results but this doesn't seem to be working and runs for way too long. Is there a better way to exclude subquery results? I tried NOT EXISTS and NOT IN but don't think I was doing it correctly as patients that should have been excluded were still showing up.
SELECT DISTINCT
pe.PAT_ENC_CSN_ID,
pe.PAT_ID,
pe.CONTACT_DATE,
vp.PAT_MRN_ID,
vp.PAT_NAME,
vp.SEX_NAME,
pat.BIRTH_DATE,
vp.AGE_YEARS,
vp.CUR_PCP_NAME
FROM PAT_ENC pe
INNER JOIN V_PAT_FACT vp on pe.PAT_ID=vp.PAT_ID
INNER JOIN PATIENT pat on vp.PAT_ID=pat.PAT_ID
INNER JOIN CLARITY_ADT adt on pe.PAT_ENC_CSN_ID=adt.PAT_ENC_CSN_ID
LEFT OUTER JOIN PAT_ENC_DX dx on pe.PAT_ID=dx.PAT_ID
LEFT OUTER JOIN CLARITY_EDG edg on dx.DX_ID=edg.DX_ID
INNER JOIN GROUPER_COMPILED_RECORDS gcr on edg.DX_ID=gcr.COMPILED_REC_LIST_VALUE
------- EXCLUSION CANCER
LEFT JOIN
(
SELECT DISTINCT pl.PAT_ID
FROM PROBLEM_LIST pl
LEFT OUTER JOIN CLARITY_EDG edg on pl.DX_ID=edg.DX_ID
INNER JOIN GROUPER_COMPILED_RECORDS rec on edg.DX_ID=rec.COMPILED_REC_LIST_VALUE
WHERE rec.GROUPER_ID in ('2100000011')
)cx on pe.PAT_ID=cx.PAT_ID
WHERE pe.CONTACT_DATE > '2016-07-01 00:00:00.000'
AND pe.WEIGHT>= '1587.3' -- 45 kg or more
AND vp.AGE_YEARS BETWEEN '40' AND '80'
AND vp.SEX_C in ('1','2') --FEMALE or MALE
AND adt.PAT_CLASS_C in ('101','103','104') ---IP, OBS or ED
AND vp.IS_VALID_PAT_YN = 'Y' -- NOT TEST
AND pat.PAT_STATUS_C <>'2' --NOT DECEASED
AND cx.PAT_ID IS NULL