【问题标题】:SQL Server show non matching recordsSQL Server 显示不匹配的记录
【发布时间】:2013-10-09 19:57:26
【问题描述】:

我有如下表。

create table #test (NAME varchar(100),TAGint,checkVAL varchar(1),CATEGORY int)

insert into #test values('jkl',1,'y',100)
insert into #test values('abc',1,'y',100)
insert into #test values('abc',1,'y',101)
insert into #test values('abc',2,'n',102)
insert into #test values('abc',3,'n',103)
insert into #test values('xyz',2,'y',104)
insert into #test values('xyz',1,'y',105)

insert into #test values('pqr',1,'y',105)
insert into #test values('pqr',1,'y',106)
insert into #test values('pqr',1,'y',106)

现在我想显示那些在 name 、 tag 、 checkVal 列中具有不同值的记录。 这就是我所做的。

select * from #test

;with cte as
(
select *,row_number() over(partition by NAME,TAG,checkVAL order by CATEGORY ) as rownum
from #test
)

select * from cte
where rownum=1

这是返回的内容

NAME    TAG  checkVAL  CATEGORY rownum
-----------------------------------------
abc     1      y       100      1
abc     2      n       102      1
abc     3      n       103      1
jkl     1      y       100      1  --> This row should not come
pqr     1      y       105      1  --> This row should not come
xyz     1      y       105      1
xyz     2      y       104      1

我正在尝试的是,对于列 NAME 中的任何值,如果 TAG 或 checkVAL 或两者中的值不同,则应该只显示这些行。

下一行

jkl     1      y       100      1 

不应显示,因为 jkl 没有其他行可匹配。

不应显示下一行

   pqr      1      y       105      1

因为 NAME 列值为pqr 的所有行在 TAGcheckVAL 列中具有相同的值

我想最好使用 CTE 。

【问题讨论】:

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


    【解决方案1】:

    这个怎么样 -

    select 
    * 
    from #test a
    where exists
    (
        select * 
        from 
        #test b
        where a.name = b.name and (a.tag <> b.tag or a.checkVAL <> b.checkVAL)
    )
    

    【讨论】:

    • 这可以通过 CTE 完成吗,我必须将解决方案插入到更复杂的程序中
    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多