SQL Server 2008 R2:仅且仅处于状态

SQL Server 2008 R2: Only and only in condition

我有以下 table 两个字段:

create table teste_r
(
colx varchar(10),
coly varchar(10)
);

插入记录:

insert into teste_r values('3','A'),('3','B'),('3','C')
                        ,('2','A'),('2','A'),('2','C')
                        ,('1','A'),('1','D');

注意:现在我想显示 colx,它只属于 A and C

所以根据要求预期的结果应该是:

预期结果

 colx    
 -----
 2

您可以像这样将 GROUP BYHAVING COUNT(DISTINCT coly) 一起使用

SELECT colx
FROM teste_r r
WHERE r.coly IN('A','C')
GROUP BY colx
HAVING COUNT(distinct coly) = (SELECT COUNT(distinct coly) FROM teste_r r2 WHERE r2.colx = r.colx)
AND COUNT(distinct coly) = 2

这是一个没有余数的关系除法的例子。您可以在这篇由 Joe Celko 撰写的 article 中获得更多信息。

你也可以看看这个 article by Dwain Camps

select  DISTINCT a.colx
from    teste_r a,
        teste_r b
WHERE   a.colx = b.colx
AND     ((a.coly = 'A' AND b.coly = 'C') OR (a.coly = 'C' AND b.coly = 'A')) 

此查询的结果如您所愿:

SELECT DISTINCT
    tr.colx
FROM dbo.teste_r AS tr
WHERE tr.colx IN (SELECT tr2.colx FROM dbo.teste_r AS tr2 WHERE tr2.coly IN ('A', 'C'))
    AND tr.colx NOT IN (SELECT tr2.colx FROM dbo.teste_r AS tr2 WHERE tr2.coly NOT IN ('A', 'C'))

您可以使用条件聚合来完成:

SELECT colx FROM teste_r
GROUP BY colx
HAVING SUM(CASE WHEN coly NOT IN('A','C') THEN 1 ELSE 0 END)=0 AND COUNT(DISTINCT coly)=2

您可以使用 not exists:

select t.colx
from teste_r t
where t.coly IN('A','C')
  and not exists ( select * 
                   from teste_r
                   where colx = t.colx
                     and coly not in ('A', 'C'))
group by t.colx
having count(distinct t.coly) = 2

SQLFiddle