0

I want to extract column A with all elements in C are in B.

T1:
+-----+-----+
|  A  |  B  |
+-----+-----+
|  a  |  1  |
|  a  |  2  |
|  a  |  3  |
|  b  |  1  |
|  b  |  2  |
|  b  |  4  |
|  c  |  2  |
|  c  |  3  |
|  c  |  4  |
+-----+-----+

T2:
+-----+
|  C  |
+-----+
|  2  |
|  4  |
+-----+

For example, b is selected because there are records (b, 2) and (b, 4). However, a is not selected because there is no (a, 4).

Desired output:

+-----+
|  A  |
+-----+
|  b  |
|  c  |
+-----+

What should I write for the condition?

select A
from T1
where ...
Noober
  • 23
  • 4

2 Answers2

0

This should achieve what you're after.

SELECT A
FROM (
  SELECT A, COUNT(*) [Count]
  FROM T1
  WHERE B IN (SELECT C FROM T2)
  GROUP BY A) t
WHERE t.[Count] >= (SELECT COUNT(*) FROM T2)

SQL Fiddle

d0little
  • 476
  • 4
  • 8
0

One method joins the two tables together and then counts the matches:

select t1.a
from t1 join
     t2
     on t1.b = t2.c
group by t1.a
having count(*) = (select count(*) from t2);

Note: If t1 can have duplicate rows, use:

having count(distinct t1.b) = (select count(*) from t2)
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786