Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to get only this condition satisfies

Author  Topic 

sqldev6363
Yak Posting Veteran

54 Posts

Posted - 2012-03-07 : 11:41:24
ID Code
1 A
1 B
1 A
1 C
2 A
2 A
2 B
3 C
3 C
3 B

In the above sample data i need a query to get the output like this.If i want to pick the IDs which are having the Code ONLY A And B. I dont need if the ID is having the Code A,B and C also.

Query should give the result only the ID 2.

ID Code
2 A
2 A
2 B

Thanks in Advance.

dev

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-03-07 : 12:34:04
[code]SELECT
Id
FROM
YourTable
GROUP BY
ID
HAVING
COUNT(DISTINCT code) = 2
AND COUNT( DISTINCT CASE WHEN code IN ('A','B') THEN code END) = 2;[/code]
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2012-03-07 : 13:23:02
SELECT * FROM yourTable o
WHERE EXISTS (SELECT * FROM YourTable i WHERE o.ID = i.ID GROUP BY ID, Code HAVING COUNT(DISTINCT ID, Code) < 3)

????



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page
   

- Advertisement -