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 ...
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.