SQL:EXCEPT查询

时间:2013-11-21 11:17:47

标签: sql sql-server tsql sql-server-2005

以下是我想要实现的基本示例:

create table #testing (
     tab varchar(max), a int, b int, c int )

insert into #testing VALUES ('x',1, 2, 3)
insert into #testing VALUES ('y',1, 2, 3)  
insert into #testing VALUES ('x', 4, 5, 6)  

select * from #testing

将产生表格:

 tab     a    b    c
-----------------------
  x      1    2    3
  y      1    2    3
  x      4    5    6

然后,我想根据a,b,c:

的值比较'tab'上的行
select a,b,c from #testing where tab = 'x'
except
select a,b,c from #testing where tab= 'y'

这给了我一个我期待的答案:

a    b    c
------------
4    5    6

但是我想在结果集中包含Tab列,所以我想要这样的事情:

 Select tab,a,b,c from #testing where ????
            (select a,b,c from #testing where tab = 'x'
             except
             select a,b,c from #testing where tab= 'y')

我将如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

使用not exists

select a.*
from #testing a
where a.tab = 'x' 
      and not exists (
                       select * 
                       from #testing t 
                       where t.a = a.a and t.b = a.b and t.c = a.c and t.tab = 'y'
                     )

在这里您可以获得SQL Fiddle演示:DEMO

答案 1 :(得分:1)

尽管@gzaxx的答案确实为这个测试数据产生了正确的结果,但是下面的通用版本更为宽泛,我在语句中留下了“x”和“y”。

select a.*
from #testing a
where not exists (
                   select * 
                   from #testing t 
                   where t.a = a.a and t.b = a.b and t.c = a.c and t.tab <> a.tab
                 )

答案 2 :(得分:1)

请尝试

 with cte as 
 (
 select *,rn = ROW_NUMBER() over(PARTITION by tab order by tab)from #testing 
 )
 select tab,a,b,c from cte where rn>1