|
- USE tempdb
- GO
- IF OBJECT_ID('TEST') IS NOT NULL
- DROP TABLE TEST;
- GO
- CREATE TABLE TEST
- (
- bh CHAR(2),
- xm VARCHAR(8)
- );
- GO
- INSERT INTO TEST VALUES('10','zhh');
- INSERT INTO TEST VALUES('20','zhh');
- INSERT INTO TEST VALUES('10','gmm');
- INSERT INTO TEST VALUES('20','gmm');
- INSERT INTO TEST VALUES('30','gmm');
- INSERT INTO TEST VALUES('10','ztt');
- INSERT INTO TEST VALUES('20','ztt');
- INSERT INTO TEST VALUES('20','yyy');
- GO
- ----------------------------------------
- ;with
- a as
- (select bh from TEST where xm='ztt'),
- b as
- (select COUNT(*) as counts from TEST where xm='ztt'),
- c as
- (select xm from TEST group by xm having COUNT(*)=(select counts from b)),
- d as
- (select t.xm from TEST as t join a on t.bh = a.bh join c on t.xm = c.xm group by t.xm having COUNT(*)=(select counts from b))
- select * from d
- ----------------------------------------
- /*
- xm
- --------
- zhh
- ztt
- (2 行受影响)
- */
- ----------------------------------------
复制代码 修改测试数据,选3门的gmm和1门的yyy都不会出现在结果中了
原理和楼上你的应该差不多 |
|