2013-11-21 32 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