-1

运行SQL Server 2012。考虑这个值集:

ID    Status
------------
11    0
11    1
11    2
12    0
12    1
12    2
13    1
14    2

如何检索按 ID 分组的相交状态值?

即因为ID=13only hasStatus=1并且ID=14only have Status=2,所以上面的数据将导致一个空行:

Status
------

但是,如果我们删除ID=14,结果将是:

Status
------
1

如果我们也删除ID=13,结果将是:

Status
------
0
1
2

更新

需要ID用任意数量的Status值来解决任意数量的问题。因此,两个SELECT查询是不够的(即使它可能适用于上面的测试数据)。

4

3 回答 3

1

这是一个关系划分问题。

NOT EXISTS如果除以一个空集,则使用双重方法返回所有。

DECLARE @S TABLE (
  [ID] INT PRIMARY KEY)

INSERT INTO @S
VALUES      (11),
            (12)

SELECT DISTINCT [Status]
FROM   YourTable Y1
WHERE  NOT EXISTS(SELECT *
                  FROM   @S
                  WHERE  NOT EXISTS (SELECT *
                                     FROM   YourTable Y2
                                     WHERE  Y1.[Status] = Y2.[Status]
                                            AND Y2.ID = [@S].ID)) 
于 2013-10-23T14:40:38.580 回答
0

此选择应适用于任何值:

select distinct status
from a a1
where (select count(distinct id) from a) = (select count(distinct id) from a a2 where a2.status = a1.status)

这是一个完整的脚本,适用于您问题中的示例数字:create table a (id int, status int)

insert a values (11, 0)
insert a values (11, 1)
insert a values (11, 2)
insert a values (12, 0)
insert a values (12, 1)
insert a values (12, 2)
insert a values (13, 1)
insert a values (14, 2)

select distinct status
from a a1
where (select count(distinct id) from a) = (select count(distinct id) from a a2 where a2.status = a1.status)

delete a where id = 14

select distinct status
from a a1
where (select count(distinct id) from a) = (select count(distinct id) from a a2 where a2.status = a1.status)

delete a where id = 13

select distinct status
from a a1
where (select count(distinct id) from a) = (select count(distinct id) from a a2 where a2.status = a1.status)
于 2013-10-23T14:14:51.313 回答
0

我认为最简单(也是最易读)的方法是这样做:

select t.status
from Table1 as t
group by t.status
having count(distinct t.id) = (select count(distinct t2.id) from Table1 as t2)

sql fiddle demo

于 2013-10-23T17:44:46.753 回答