关于分组加顺序号的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

可以这样:

alter table work_proc add id int IDENTITY (1,1)

update work_proc
set other =1+isnull((select count(*) from work_proc where thid=a.thid and id < a.id),0)
from work_proc as a

alter table work_proc drop COLUMN id

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

Try this:

DECLARE @Thid CHAR(1)
,@Other INT

SET @Other=0
UPDATE YourTableName
SET @Other=CASE WHEN @Thid=Thid THEN @Other+1 ELSE Other END
,@Thid=CASE WHEN COALESCE(@Thid,'')=Thid THEN @THid ELSE Thid END
,Other=@Other

FROM YourTableName

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus