从重复组中查找相交值?

时间:2013-10-23 14:05:29

标签: sql sql-server tsql

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

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

如何检索在ID上分组的交叉状态值?

即。由于ID=13只有Status=1ID=14只有Status=2,因此上述数据会导致空行:

Status
------

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

Status
------
1

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

Status
------
0
1
2

更新

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

3 个答案:

答案 0 :(得分:1)

这是relational division问题。

如果除以空集,则使用双NOT EXISTS方法返回all。

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)) 

答案 1 :(得分: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)

答案 2 :(得分: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