日期:2014-05-18  浏览次数:20422 次

如何解决字段重复的记录
SQL得到如下记录集。如何让NA重复的记录中用NULL值表示?谢谢!

NA CJ KM
--------------------
a 2 a2 
a 1 a1 
a 3 a3 
b 1 b1 
b 3 b3 
b 2 b2 
b 4 b4 
b 5 b5 

想得到以下格式:

NA CJ KM
--------------------
a 2 a2 
null 1 a1 
null 3 a3 
b 1 b1 
null 3 b3 
null 2 b2 
null 4 b4 
null 5 b5 



------解决方案--------------------
用程序
------解决方案--------------------
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([NA] varchar(1),[CJ] int,[KM] varchar(2))
insert [tb]
select 'a',2,'a2' union all
select 'a',1,'a1' union all
select 'a',3,'a3' union all
select 'b',1,'b1' union all
select 'b',3,'b3' union all
select 'b',2,'b2' union all
select 'b',4,'b4' union all
select 'b',5,'b5'
go

select case when rn=1 then na end as na,cj,km
from
(select rn=row_number() over(partition by na order by getdate()),* from tb)t

/**
na   cj          km
---- ----------- ----
a    2           a2
NULL 1           a1
NULL 3           a3
b    1           b1
NULL 3           b3
NULL 2           b2
NULL 4           b4
NULL 5           b5

(8 行受影响)
**/

------解决方案--------------------
探讨

SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([NA] varchar(1),[CJ] int,[KM] varchar(2))
insert [tb]
select 'a',2,'a2' union all
select 'a',1,'a1' union all
select 'a……

------解决方案--------------------
探讨
引用:

SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([NA] varchar(1),[CJ] int,[KM] varchar(2))
insert [tb]
select 'a',2,'a2' union all
select 'a',1,'a1' ……