4

I have a table with rows with two columns

A 1
A 2
B 1
B 3
C 1
C 2
C 3

and I want to get from this only this ID(a,b or c) which has only 2 rows with value 1,2, so from this table I should get a, bacause b hasn't row with 2, and c has rows with 1 and b, but also has row with c..

What is the simplest way to get this row?

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
user278618
  • 19,306
  • 42
  • 126
  • 196

2 Answers2

6
SELECT col1
FROM YourTable
GROUP BY col1
HAVING COUNT(DISTINCT col2) =2 AND MIN(col2) = 1 AND MAX(col2) = 2

Or another way extendible to more than 2 numbers

SELECT col1
FROM   yourtable
GROUP  BY col1
HAVING MIN(CASE
             WHEN col2 IN ( 1, 2 ) THEN 1
             ELSE 0
           END) = 1
       AND COUNT(DISTINCT col2) = 2 
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
0
select t1.col1 
from table as t1 
left join table as t2 on (t1.col1 = t2.col1) 
where t1.col2 = 1 and t2.col2 = 2;
Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
Gene
  • 1