Skip to content
Advertisement

SQL – Matching only the values in IN clause (not less or more)

I am having the following ManyToMany table TEAM_USERS with the below data:

TEAM_ID     USER_ID
1           10
1           3
1           4
1           11
12          10
12          3
12          4
11          3
11          4
18          10
18          7
18          4
18          11

So, I want to get the TEAM_ID that is having only two user with the USER_ID IN (3, 4), in this case it’s team 11. But I am getting team 1, 11, and 12. And I want only team 11.

I did the following code but I am not getting the expected results

SELECT  team_id
FROM    team_users 
WHERE   user_profile_id IN (3 , 4)
GROUP   BY team_id
HAVING  COUNT(DISTINCT user_profile_id) = 2;

the results for this query is:

TEAM_ID
1
11
12

So, please any help would be really appreciated.

=============== EDIT: The list is unique, and there is no duplicates

Advertisement

Answer

Move the WHERE-condition into conditional aggregation.

As long as the combination team_id/user_profile_id is unique:

select team_id
from team_users 
group by team_id
-- exactly those two and no other
having sum(case when user_profile_id in (3, 4) then 1 else -1 end) = 2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement