【小小问题集锦13之---关于分组加顺序号的SQL写法】

/*

原表:  
thid      other  
a              1  
a              1  
b              0  
b              0  
b              0  
c              2    
c              2  
希望变成:  
thid      other  
a              1  
a              2  
b              0  
b              1  
b              2  
c              2    
c              3  

*/

if OBJECT_ID('tb') is not null

drop table tb 

go

create table tb (id varchar(10) ,value int)

insert tb select 

'a'  ,            1  union all select 

'a'  ,            1  union all select

'b'  ,            0  union all select

'b'  ,            0  union all select

'b'  ,            0  union all select

'c'  ,            2  union all select 

'c'  ,            2  

go

--方法:update

DECLARE  @id CHAR(1),@value  INT  

SET  @value=0  

UPDATE tb 

SET @value=CASE  WHEN  @id=id  THEN  @value+1  ELSE  value  END  

  ,@id=CASE  WHEN  COALESCE(@id,'')=id  THEN  @id  ELSE  id  END  

  ,value=@value  

FROM  tb

go

--方法:显示

    --2000.

    select IDENTITY(int,1,1) as rn,* into # from tb 

    select ID,[values]=(select MIN(value) from # where K.id=ID)+(select COUNT(*) from # where K.id=ID and rn<k.rn )

    from # k

--2005

;with cte as

(

select rn=ROW_NUMBER()over(order by getdate()),* from tb 

)

    select ID,[values]=(select MIN(value) from cte where K.id=ID)+(select COUNT(*) from cte where K.id=ID and rn<k.rn )

    from cte  k

go

/*

ID         values

---------- -----------

a          1

a          2

b          0

b          1

b          2

c          2

c          3*/

你可能感兴趣的:(sql,c)