我在测试表下面有数据:
Create table test
(
col1 int,
col2 int
)
示例数据:
col1 col2
-------------
1 4
1 5
2 4
3 5
3 4
现在我想要col2值为4和5的所有col1 o / p 1,3因为它包含4个以及5个col2值
答案 0 :(得分:1)
SELECT *
FROM TestTable
WHERE col1 IN
(
SELECT col1
FROM TestTable
WHERE col2 = 4
)
AND col2 = 5
答案 1 :(得分:0)
如果您只需要col1值,则可以
当然,having子句中的值(本例中为2)取决于IN子句中元素的数量(所以如果你有3,4,5,你需要在having子句中加上3 )
select col1 from test t1
where col2 in (4, 5)--take only results with 4 and 5 in col2
group by col1
having count(distinct col2) = 2 --be sure there's at least a 4 and a 5