Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get common records

I have a table as below

ID  Username GroupID
1   venkat     2
2   venkat     3
3   ramu       1
4   ramu       2

Using the sql statement I want to retrieve all username's that are available in both the groupids 2,3

In this case only Venkat is the username that's available in both groupid 2 and 3

Kindly help me

like image 732
Tarak Avatar asked Dec 24 '13 12:12

Tarak


1 Answers

Try this:

SELECT userName
FROM tableA 
WHERE groupId IN (2, 3)
GROUP BY userName 
HAVING COUNT(DISTINCT groupId) = 2;

Check the SQL FIDDLE DEMO

OUTPUT

| USERNAME |
|----------|
|   venkat |
like image 78
Saharsh Shah Avatar answered Nov 02 '22 07:11

Saharsh Shah