【发布时间】: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 的所有行在 TAG 和 checkVAL 列中具有相同的值
我想最好使用 CTE 。
【问题讨论】:
标签: sql sql-server sql-server-2005