0

考虑下表的 A 列和 B 列:

A | B  
--+--  
1 | A  
1 | B  
1 | C  
2 | A  
2 | B  
3 | A  
3 | C  
4 | B  
4 | C  

如果我的集合是 [A,B],我想从 A 列获取值 2。

IN
select a from table where b IN ('A','B'),这将返回值 1 和 2。

Intersect,这将返回 1 但是如果我删除'B'标准并且只查找[A,C],它将不起作用。这样的查询将返回 1 和 3。
select a from table where b = 'A'
intersect
select a from table where b = 'B'
intersect
select a from table where b = 'C'

有没有更聪明的方法来使用具有一对多关系的集合,或者可能是我没有想到的另一种方法?顺便说一句,我将使用 Oracle,以防有任何 Oracle 特定的解决方案可用。

编辑:使用它进行测试:SQLFiddle Link

4

2 回答 2

1

这是“set-within-sets”查询的一个示例。我喜欢使用聚合和having每个条件的子句来解决这些问题。在这种情况下,存在三个条件: A 的给定值是否具有值为“A”的 B?对于'B'?为了别的?

这导致查询:

select A
from t
group by A
having sum(case when B = 'A' then 1 else 0 end) > 0 and
       sum(case when B = 'B' then 1 else 0 end) > 0 and
       sum(case when B not in ('A', 'B') then 1 else 0 end) = 0;
于 2013-09-18T12:51:45.290 回答
0

尝试这个

select A 
from t
group by A
having count(*)=2 and min(B)='A' and Max(B)='B'
于 2013-09-18T21:20:18.350 回答