如何找到同时具有A类和B类的contract_id
?
record contract_id type
1 1 A
2 1 B
3 2 A
4 2 A
5 3 B
6 3 B
在这里,我希望我们能找到contract_id
1,因为它同时具有A类和B类。
非常感谢你。
答案 0 :(得分:2)
您可以使用GROUP BY
和HAVING
:
SELECT contract_id
FROM YourTable
WHERE type IN ('A','B')
GROUP BY contract_id
HAVING COUNT(DISTINCT type) = 2
答案 1 :(得分:0)
您可以在子查询上使用INNER JOIN
选择A
和B
记录:
SELECT a.contract_id
FROM
(SELECT record, contract_id
FROM Contract_type
WHERE [type] = 'A') as a
INNER JOIN
(SELECT record, contract_id
FROM Contract_type
WHERE [type] = 'B') as b
ON a.contract_id = b.contract_id