ORACLE,我如何在同一个表中使用两个不同的过滤器?

时间:2018-06-19 11:06:40

标签: sql database oracle

我有这个问题:在同一张桌子中,我需要同时只有两个CODES才能获得ID,EX:

TABLE1

ID | CODE
1  | A
1  | B
2  | C
2  | B
3  | C
3  | A
4  | A
5  | C

示例:我需要同时获取代码为“A”和“B”的ID,在TABLE1中,答案只是ID 1

所以我算什么ID有两个CODE:

SELECT ID
FROM TABLE1
GROUP BY ID
HAVING COUNT(CODE) = 2

我过滤CODE的是'A'OR'B'

SELECT ID
FROM TABLE1
WHERE (CODE = 'A' OR 'B')

但我如何结合这两个查询?

4 个答案:

答案 0 :(得分:2)

A slight variation on the answer given by @Lukasz:

SELECT ID
FROM TABLE1
WHERE Code IN ('A', 'B')
GROUP BY ID
HAVING COUNT(DISTINCT Code) = 2;

答案 1 :(得分:2)

Your question is a little ambiguous. If you want A/B together -- and other codes are allowed as well -- then:

SELECT ID
FROM TABLE1
WHERE CODE IN ('A', 'B')
GROUP BY ID
HAVING MIN(CODE) = 'A' and MAX(CODE) = 'B';

You can also use:

HAVING COUNT(DISTINCT CODE) = 2;

However, COUNT(DISTINCT) typically has worse performance.

答案 2 :(得分:0)

您可以使用条件聚合:

SELECT ID
FROM TABLE1
GROUP BY ID 
HAVING COUNT(DISTINCT CASE WHEN Code IN('A','B') THEN Code END) = 2;

<强> DBFiddle Demo

答案 3 :(得分:0)

You can do :

select t1.*
from table1 t1
where not exists (select 1 from table1 t2 where t2.id = t1.id and t2.code = 'C');