2013-11-21 30 views
2

这里是什么,我想实现一个基本的例子:SQL:除非查询

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的值:

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 

不过我想也包括标签列在我的结果集,所以我想财产以后这样的:

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

我将如何实现这一目标?

回答

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小提琴演示:DEMO

+0

工程完全按照要求,谢谢。 –

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