Use conditional aggregation:
SELECT t1.* FROM yourTable t1 INNER JOIN ( SELECT ADV_ID, CASE WHEN COUNT(CASE WHEN USER_ID = 3 THEN 1 END) > 0 THEN 3 END USER_ID FROM yourTable ) t2 ON t1.ADV_ID = t2.ADV_ID AND ((t1.USER_ID IS NULL AND t2.USER_ID IS NULL) OR (t1.USER_ID = t2.USER_ID)) WHERE t1.ADV_ID = 22;
Explanation: the subquery that I generated as t2 aggregates by ADV_ID and displays the value 3 if this value occurs in one or more records, otherwise it returns NULL . Then we attach this subquery to the original table, provided that both USER_ID NULL , or, if not, match two USER_ID values.
You can change the demo to see that it generates the output you want for other inputs.
source share