JustinReid
JustinReid

Reputation: 192

SQL to return matches from multiple queries

I need to return values that appear across two or more queries from the same table. Feeling a bit like a noob here but just can't see the wood for the trees.

I have a table of users assigned to different groups. I need to return only the users that appear in all of the requested groups:

User   Group
frank  1
Jane   2
Tom    2
frank  2
Jane   1
Tom    3

This is want I need to output:

Result for Group 1 & 2:
frank
Jane

Result for Group 2 & 3:
Jane
Tom

Seems a very 101 question, but grateful for any pointers.

Upvotes: 2

Views: 231

Answers (2)

Madhivanan
Madhivanan

Reputation: 13700

select user from table
where group in (1,2)
group by user
having count(distinct group)=2

Upvotes: 3

user330315
user330315

Reputation:

select user
from users
where group_id in (1,2)
group by user
having count(*) = 2;

You need to adjust the having count(*) = 2 condition to the number of groups that you want.

If a user can be assigned to the same group more than once, then Madhivanan's comment need to be taken into account:

select user
from users
where group_id in (1,2)
group by user
having count(distinct group_id) = 2;

(I used the column name group_id because group is a reserved word and should be used as a column name).

Upvotes: 3

Related Questions