我有这个问题:在同一张桌子中,我需要同时只有两个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')
但我如何结合这两个查询?
答案 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');