SQL Query to get common records

2019-03-31 04:34发布

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

2条回答
2楼-- · 2019-03-31 04:57

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 |
查看更多
你好瞎i
3楼-- · 2019-03-31 05:06

An alternate approach using a plain JOIN;

SELECT DISTINCT t1.username 
FROM MyTable t1 JOIN MyTable t2
  ON t1.username = t2.username AND t1.groupid=2 AND t2.groupid=3;

An SQLfiddle to test with.

查看更多
登录 后发表回答