SQL检测部分重复的行

时间:2012-03-05 15:46:01

标签: sql

我有一张表:

ID X
1  YES
1  YES
2  YES
2  YES
2  NO
3  NO
4  NO
4  YES

我需要返回同时包含YesNo的所有ID,因此最终结果应该是2和4但不是2和3

4 个答案:

答案 0 :(得分:4)

SELECT ID
    FROM YourTable
    WHERE X IN ('YES', 'NO')
    GROUP BY ID
    HAVING COUNT(DISTINCT X) = 2

答案 1 :(得分:3)

试试这个:

select id from t
where x in ('YES', 'NO')
group by id
having count(distinct x) = 2

这是working example

另请注意,如果您的表中只有'YES'和'NO'值(如您的示例中所示),则可以删除where子句,因为它将是不必要的且效率较低。

答案 2 :(得分:2)

SELECT DISTINCT ID FROM myTable
WHERE X = 'YES'
     AND ID IN (SELECT DISTINCT ID FROM myTable WHERE X = 'NO')

答案 3 :(得分:0)

另一种选择:

SELECT DISTINCT id
  FROM t t1
  JOIN t t2 USING(id)
 WHERE t1.X = 'YES' AND t2.X = 'NO'