SQL:除了查询

SQL:除了查询,sql,sql-server,tsql,sql-server-2005,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 将生成以下表格

以下是我试图实现的一个基本示例:

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')
如何实现这一点?

使用不存在:


这里是SQL Fiddle演示:

虽然@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
                 )
请试一试

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