SELECT * FROM table1 t1 left outer join table2 t2 on t1.id = t2.id and t2.col4 = 5 where t2.id is null group by t1.col2 having sum(col3) >= 0
External selection is missing from the FROM and does not add anything, so I deleted it. NOT IN inefficient compared to the LEFT OUTER JOIN method, so I replaced it. Two UNION were easily combined into one using >= .
Update: Note the use of UNION ALL , not UNION . I donβt think you want to remove duplicates, and it will work faster this way.
SELECT AVG(t1.col5) FROM table1 t1 left outer join table2 t2 on t1.id = t2.id and t2.col4 = 5 where t2.id is null group by t1.col2 having sum(t1.col3) > 0 UNION ALL SELECT MAX(t1.col5) FROM table1 t1 left outer join table2 t2 on t1.id = t2.id and t2.col4 = 5 where t2.id is null group by t1.col2 having sum(t1.col3) = 0
source share