34,594
社区成员
发帖
与我相关
我的任务
分享
---------------------------------------------
--> Author : js_szy
--> Target : ★★★
--> Date : 2010-01-05 10:06:07
--> Version: SQL Server 2005
---------------------------------------------
--> 测试数据: @tb
declare @tb table (id int,e_Id varchar(3),s_id varchar(2))
insert into @tb
select 1,'001','01' union all
select 2,'001','02' union all
select 3,'001','08' union all
select 4,'002','01' union all
select 5,'002','02' union all
select 6,'003','02' union all
select 7,'003','06'
select s_id from @tb t
group by s_id
having(count(*)=(select count(distinct e_id) from @tb))
s_id
----
02
(1 行受影响)
create table tb(id int, e_Id varchar(10), s_id varchar(10))
insert into tb values(1 , '001' , '01')
insert into tb values(2 , '001' , '02')
insert into tb values(3 , '001' , '08')
insert into tb values(4 , '002' , '01')
insert into tb values(5 , '002' , '02')
insert into tb values(6 , '003' , '02')
insert into tb values(7 , '003' , '06')
go
select s_id from tb group by s_id having count(1) = (select count(distinct e_id) from tb)
drop table tb
/*
s_id
----------
02
(所影响的行数为 1 行)
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[e_Id] varchar(3),[s_id] varchar(2))
insert [tb]
select 1,'001','01' union all
select 2,'001','02' union all
select 3,'001','08' union all
select 4,'002','01' union all
select 5,'002','02' union all
select 6,'003','02' union all
select 7,'003','06'
SELECT S_ID FROM TB
GROUP BY S_ID
HAVING COUNT(1)=(SELECT COUNT(DISTINCT e_id) FROM TB)
(所影响的行数为 7 行)
S_ID
----
02
(所影响的行数为 1 行)
SELECT S_ID FROM TB
GROUP BY S_ID
HAVING COUNT(1)=(SELECT COUNT(DISTINCT e_id) FROM TB)
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[e_Id] varchar(3),[s_id] varchar(2))
insert [tb]
select 1,'001','01' union all
select 2,'001','02' union all
select 3,'001','08' union all
select 4,'002','01' union all
select 5,'002','02' union all
select 6,'003','02' union all
select 7,'003','06'
---查询---
select s_id
from tb
group by s_id
having count(distinct e_id)=(select count(distinct e_id) from tb)
---结果---
s_id
----
02
(所影响的行数为 1 行)
SELECT S_ID FROM TB
GROUP BY S_ID
HAVING COUNT(1)=(SELECT COUNT(DISTINCT e_id) FROM TB)