2013-10-09 121 views
0

我有如下表格。SQL Server显示不匹配的记录

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) 

现在我想告诉那些在列名称,标签,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 

什么我想的是,对于列名的值,如果值是TAG或checkVAL或两者不同,则这些行只应所示。

下面

jkl  1  y  100  1 

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

以下行不应显示

pqr  1  y  105  1 

因为NAME列值pqr所有行TAGcheckVAL有相同的价值观

我想最好的办法使用CTE。

回答

3

这个怎么样 -

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

+1简单而完美的答案! –

+0

这可以通过CTE来完成,我必须将解决方案插入到更复杂的程序 –

+0

感谢好友..设法使用您的解决方案.. –

相关问题