The first part of the query before not in
runs and gives me a list of
Purely stylistic: you can "squeeze out" the patientICD*tblICD product, and put it into a CTE, and reference that twice, like: (untested)
WITH zzz AS (
SELECT pic.patientid , pic.admissiondate , pic.dischargedate
, tab.ICD_ID , tab.descrip
FROM patientICD pic
JOIN tblICD tab ON pic.primarycode = tab.ICD_ID
)
SELECT DISTINCT p.patientid
FROM Patient p
JOIN zzz one ON one.patientid = p.patientid
AND one.admissiondate = p.admissiondate
AND one.dischargedate = p.dischargedate
WHERE one.descrip LIKE N'%diabetes%'
AND p.patientid NOT IN (
SELECT two.patientid
FROM zzz two
WHERE two.admissiondate = p.admissiondate
AND two.dischargedate = p.dischargedate
AND two.icd_id LIKE N'25000'
);
NOTE: I don't like the LIKE N'25000'
. I think an exact match would be fine. And the icd_id-field should be numeric, probably. And the {admissiondate,dischargedate} pair should be modelled out, too; possibly by using a diagnosis_id or incident_id.