问题描述
我有一个表Table1,其中有A列和B列(很多表)。
|---------------------|------------------|
| ColumnA | ColumnB |
|---------------------|------------------|
| a1 | b1 |
|---------------------|------------------|
| a1 | b2 |
|---------------------|------------------|
| a2 | b1 |
|---------------------|------------------|
| a2 | b3 |
|---------------------|------------------|
| a3 | b2 |
|---------------------|------------------|
我想要一个A
个列表,其中B
个仅在B
个列表中。
因此,在上表中,如果列表为[b1,b2]
期望 [a1,a3]
不包括a2
,因为它也与b3
相关联。
解决方法
您可以使用聚合并具有:
select a
from ab
group by a
having sum(case when b not in ('b1','b2') then 1 else 0 end) = 0;
having
子句正在检查列表中 not 的行数。 = 0
说没有。
假设2*j
中没有空值,则可以使用ColumnB
:
NOT EXISTS
如果只需要select t.*
from tablename t
where not exists (select 1 from tablename where ColumnA = t.ColumnA and ColumnB not in ('b1','b2'))
的不同值:
ColumnA
请参见demo。