查找其他列中具有多个值的记录

时间:2016-08-31 20:32:57

标签: sql

如何找到同时具有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类。

非常感谢你。

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP BYHAVING

SELECT contract_id
FROM YourTable
WHERE type IN ('A','B')
GROUP BY contract_id
HAVING COUNT(DISTINCT type) = 2

答案 1 :(得分:0)

您可以在子查询上使用INNER JOIN选择AB记录:

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