日期:2014-05-17  浏览次数:20464 次

SQL 语句难题,根据一个字段,重复的都给它一个自增编码。
根据一个字段,重复的都给它一个自增编码。如表text:
字段一      字段二 
80         i
80         h
80         j
···
90         k
90         h
90         i
···

用select语句 增加一个字段三变成:字段三给字段一相同的编序号。
字段一      字段二    字段三
80         i        2
80         h        3
80         j        4
···
90         k        2
90         h        3
90         i        4
····
不知道大神明白了我的意思了没有。根据字段一相同的,给他编号。从2开始编号,在sql server数据库里面的。
真的不好意思,最高只能给一百分。系统限制了。


------解决方案--------------------
create table tb(id int,val varchar(10),id2 int)
insert into tb(id,val)
select 80,'i'
union all select 80,'h'
union all select 80,'j'
union all select 80,'g'
union all select 80,'p'
union all select 80,'x'
union all select 80,'q'
union all select 90,'k'
union all select 90,'h'
union all select 90,'i'
union all select 90,'m'
union all select 90,'t'
union all select 90,'y'


declare @i int,@id int
set @id=0
set @i=1
update tb
set @i=case when @id=id then @i+1 else 2 end,@id=case when @id=id then @id else id end,id2=@i

select * from tb
drop table tb