【问题标题】:SQL: EXCEPT QuerySQL:除了查询
【发布时间】:2013-11-21 11:17:47
【问题描述】:

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

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

但是我还想在我的结果集中包含 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 sql-server tsql sql-server-2005


    【解决方案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

    【讨论】:

      【解决方案2】:

      尽管来自@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
                       )
      

      【讨论】:

        【解决方案3】:

        请尝试一下

         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
        

        【讨论】:

          猜你喜欢
          • 2020-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-07
          • 2021-06-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多