我有一张像
这样的表格letter | number
a | 1
a | 1
b | 2
c | 1
c | 2
c | 2
我想编写一个SQL查询,它只返回与数字'1'和数字'2'相关联的字母值对应的行,即我只想保留
c | 1
c | 2
c | 2
来自我上面的例子。
有人可以帮忙吗?非常感谢!
答案 0 :(得分:1)
您需要使用Group By
和Having
子句
这会为您提供与号码letters
和1
相关联的2
SELECT *
FROM yourtable
WHERE letter IN (SELECT letter
FROM yourtable
WHERE number IN ( 1, 2 )
GROUP BY letter
HAVING Count(DISTINCT number) = 2)
如果您想找到与letters
和1
仅关联的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