列1 列2
1 a
2 b
1 b
4 b
1 c
6 a
6 b
6 c
我想查询同时满足第二列的值为 a,b,c的值,如上表所示,同时满足上表的应该是两条记录,1和6。
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-06-11 16:29:06
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([列1] int,[列2] nvarchar(2))
insert [huang]
select 1,'a' union all
select 2,'b' union all
select 1,'b' union all
select 4,'b' union all
select 1,'c' union all
select 6,'a' union all
select 6,'b' union all
select 6,'c'
--------------生成数据--------------------------
select 列1
from [huang]
WHERE [列2] IN ( 'a','b','c')
GROUP BY 列1
HAVING COUNT(1)=3
----------------结果----------------------------
/*
列1
-----------
1
6
*/
------解决方案--------------------
create table mr(列1 int,列2 varchar(10))
insert into mr
select 1,'a' union all
select 2,'b' union all
select 1,'b' union all
select 4,'b' union all
select 1,'c' union all
select 6,'a' union all
select 6,'b' union all
select 6,'c'
select distinct a.列1
from mr a
where exists(select 1 from mr b where b.列1=a.列1 and b.列2='a')
and exists(select 1 from mr b where b.列1=a.列1 and b.列2='b')
and exists(select 1 from mr b where b.列1=a.列1 and b.列2='c')
/*
列1
-----------
1
6
(2 row(s) affected)
*/
------解决方案--------------------
黄版这个思路有点错误,in ( 'a','b','c')如果是2个a,3个a的记录也会满足,而楼主要的是满足abc。我想了个投机取巧的办法是,把字母转成ASCII码相加判总和,来确定是否有缺失