I'm surprised it is taking that long - but it is a large dataset
Check that relevant columns are indexed AccessIDCode, PatientLinkCode, CCPXCode and ServiceEndDate
After that, two things to try.
1. I may have missed something so assuming the 'success' query is called query1 try this code
Code:
SELECT YAGPRUNED.*
FROM YAGPRUNED LEFT JOIN Query1
ON YAGPRUNED.AccessIDCode=Query1.AccessIDCode
WHERE Query1.AccessIDCode is Null
2. If that doesn't work, change the 'success' query to a make table query and make a table called say 'success'. Ensure the AccessIDCode in this table is indexed. Then use the following code
Code:
SELECT YAGPRUNED.*
FROM YAGPRUNED LEFT JOIN Success
ON YAGPRUNED.AccessIDCode=Success.AccessIDCode
WHERE Success.AccessIDCode is Null
The other thing that may be slowing it up is the CCPXCode IN component
it might be you can speed things up by creating a new column called say CCPXGroup (make sure it is type number and indexed) and run an update query to update this column with 1 for "27.3 A", "26.98A", "26.52A" and 2 for the others e.g.
Code:
UPDATE YAGPRUNED
SET CCPXGroup=choose(CCPXCode IN ("27.3 A", "26.98A", "26.52A"),1,CCPXCode IN ("28.2 B", "28.2 C", "28.4 A", "28.4 B", "28.5 A", "28.71A", "28.72B", "28.74A", "28.74B"),2)
and then your success query would become
Code:
SELECT *
FROM YAGPRUNED
WHERE
(CCPXGroup=1 AND not Exists(SELECT * FROM YAGPRUNED AS T WHERE PatientLinkCode=YAGPRUNED.PatientLinkCode AND CCPXGroup=2 AND ServiceEndDate=YAGPRUNED.ServiceEndDate))
OR
(CCPXGroup=2 AND not Exists(SELECT * FROM YAGPRUNED AS T WHERE PatientLinkCode=YAGPRUNED.PatientLinkCode AND CCPXGroup=1 AND ServiceEndDate=YAGPRUNED.ServiceEndDate))
Just had another though which could be quicker - (based on the CCPXGroup suggestion) which should work is
Code:
SELECT YAGPRUNED.*
FROM (YAGPRUNED LEFT JOIN (SELECT * FROM YAGPRUNED AS T WHERE CCPXGroup=1) AS Grp1 ON YAGPRUNED.PatientLinkCode=Grp1.PatientLinkCode AND YAGPRUNED.ServiceEndDate=Grp1.ServiceEndDate) LEFT JOIN (SELECT * FROM YAGPRUNED AS T WHERE CCPXGroup=2) AS Grp2 ON YAGPRUNED.PatientLinkCode=Grp2.PatientLinkCode AND YAGPRUNED.ServiceEndDate=Grp2.ServiceEndDate
WHERE
(GRP1.AccessLinkCode is Null AND Grp2.AccessLinkCode is Null)
If you don't want to go the CCPXGroup route then replace
CCPXGroup=1 with CCPXCode IN ("27.3 A", "26.98A", "26.52A") and
CCPXGroup=2 with CCPXCode IN ("28.2 B", "28.2 C", "28.4 A", "28.4 B", "28.5 A", "28.71A", "28.72B", "28.74A", "28.74B")
Hope all that is not too confusing!