请问SQL语句如何写
ID GroupID KeyID
1 6 20
2 6 21
3 6 22
4 7 29
5 7 30
6 8 20
7 8 21
8 8 29
9 10 20
请问如何找出 KEYID 既有20,又有21的groupID,即结果应该是
GroupID
6
8
SQL语句如何写 sql
[解决办法]
select groupID from tb where KEYID=20
intersect
select groupID from tb where KEYID=21
[解决办法]
把t2換成你的子查詢。
USE test
GO
-->生成表t1
if object_id('t1') is not null
drop table t1
Go
Create table t1([ID] smallint,[GroupID] smallint,[KeyID] smallint)
Insert into t1
Select 1,6,20
Union all Select 2,6,21
Union all Select 3,6,22
Union all Select 4,7,29
Union all Select 5,7,30
Union all Select 6,8,20
Union all Select 7,8,21
Union all Select 8,8,29
Union all Select 9,10,20
Union all Select 10,6,29-- test
-->生成表t2
if object_id('t2') is not null
drop table t2
Go
Create table t2([keyID] smallint)
Insert into t2
Select 20
Union all Select 21
Union all Select 29
SELECT
GroupID
FROM t1 AS a
INNER JOIN t2 AS b ON a.KeyID=b.keyID
GROUP BY
GroupID
HAVING COUNT(1)=(SELECT COUNT(1) FROM t2)
/*
GroupID
-------
6
8
*/