SQL:对多行进行条件查询

时间:2015-07-30 16:44:51

标签: sql

我有一张像

这样的表格
letter | number
a      | 1
a      | 1
b      | 2
c      | 1
c      | 2
c      | 2

我想编写一个SQL查询,它只返回与数字'1'和数字'2'相关联的字母值对应的行,即我只想保留

c | 1
c | 2
c | 2

来自我上面的例子。

有人可以帮忙吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

您需要使用Group ByHaving子句

这会为您提供与号码letters1相关联的2

SELECT * 
FROM   yourtable 
WHERE  letter IN (SELECT letter 
                  FROM   yourtable 
                  WHERE  number IN ( 1, 2 ) 
                  GROUP  BY letter 
                  HAVING Count(DISTINCT number) = 2) 

如果您想找到与letters1 关联的2,请使用此

SELECT letter 
FROM   test 
GROUP  BY letter 
HAVING Count(DISTINCT CASE WHEN number = 1 THEN 1 END) = 1 
       AND Count(DISTINCT CASE WHEN number = 2 THEN 1 END) = 1 
       AND Count(DISTINCT number) = 2