读书人

请教SQL语句怎么写

发布时间: 2013-02-06 14:02:21 作者: rapoo

请问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
*/

[解决办法]

select KeyID into #tb from 你那个表 --
declare @bl int
declare @sql varchar(4000)
if exists(select top(1)1 from #tb)
begin
select @bl=KeyID from #tb
set @sql=@sql+' select groupID from tb where KEYID='+@bl+'intersect'
delete #tb where KeyID=@bl
end
set @sql=substring(@sql,1,len(9))
exec(@sql)

没测试过,大概的思路就这样,你自己改改吧

读书人网 >SQL Server

热点推荐