Hi hoping to have help to optimize the query below, it is taking 4+ hours to run when comparing two larger tables with 55k and 1.6M rows respectively.
I have 2 tables Oppty and Acc and a query to derive the "CF" field (fiddle https://dbfiddle.uk/sRT7-kvz)
And below have a query deriving where if there is NO match in Account_ID between the tables it will say 'No Match @ ACC_ID Level'
- If there IS a match at the ACC_ID level then, it will look at Prod1 match (anywhere in that ACC_ID), if NO Prod1 match it will just say 'Match @ ACC_ID Level'
- If there IS a match at the ACC_ID and Prod1 level then it will look at Prod2 match (anywhere in that ACC_ID) and if NO is Prod2 match it will say 'Match @ ACC_ID, Prod1 Levels', and if there IS a Prod2 match it will say 'Match @ ALL Levels'
SELECT
op."Acc_ID"
, op."Oppty_ID"
, op."Prod1op"
, op."Prod2op"
, CASE WHEN EXISTS (
SELECT 1
FROM Acc ac
WHERE ac."Acc_ID" = op."Acc_ID")
THEN
CASE WHEN EXISTS (
SELECT 1
FROM Acc ac
WHERE ac."Acc_ID" = op."Acc_ID"
AND ac."Prod1acc" = op."Prod1op")
THEN
CASE WHEN EXISTS (
SELECT 1
FROM Acc ac
WHERE ac."Acc_ID" = op."Acc_ID"
AND ac."Prod1acc" = op."Prod1op"
AND ac."Prod2acc" = op."Prod2op")
THEN 'Match @ ALL Levels'
ELSE 'Match @ ACC_ID, Prod1 Levels' END
ELSE 'Match @ ACC_ID Level' END
ELSE 'No Match @ ACC_ID Level' END CF
FROM Oppty op
ORDER BY op."Acc_ID", op."Prod1op"