创建表
create table test
(  
   id int identity(1,1) not null,
   a int not null,
   b char(1) not null,
)插入数据
insert into test values (0,'A') 
insert into test values (0,'B')
insert into test values (0,'B')
insert into test values (0,'A')
insert into test values (0,'B')现在表里面的数据就是
id    a      b
1     0      A
2     0      B
3     0      B
4     0      A
5     0      B怎么通过SQL修改语句把表里面的a列数据变成
id    a      b
1     1      A
4     2      A
2     1      B
3     2      B
5     3      B当然表里面不止这几条数据,怎么样做循环判断给b列相同的数据标上a列中的数字?

解决方案 »

  1.   

    ;with tmp
    as
    (select rn=row_number()over(partition by b order by id),
    *
    from test)
    update tmp
    set a=rn
      

  2.   

    update t
    set a=(select count(*) from test where b=t.b and id<=t.id)
    from test t
    go
      

  3.   

    --创建表go 
    if OBJECT_ID('test') is not null
    drop table test
    go
    create table test
    (  
      id int identity(1,1) not null,
      a int not null,
      b char(1) not null
    )--插入数据
    go
    insert into test values (0,'A') 
    insert into test values (0,'B')
    insert into test values (0,'B')
    insert into test values (0,'A')
    insert into test values (0,'B')/*
    现在表里面的数据就是
    id a b
    1 0 A
    2 0 B
    3 0 B
    4 0 A
    5 0 B怎么通过SQL修改语句把表里面的a列数据变成
    id a b
    1 1 A
    4 2 A
    2 1 B
    3 2 B
    5 3 B
    */
    drop table #t
    go
    create table #t(
    id int not null,
      a int not null,
      b char(1) not null
    )
    go
    insert #t
    select id,
    ROW_NUMBER() over(partition by b order by b) as a,b 
    from test 
    select *from #t
    --我只会这样,把你的原表的数据放到临时表中,
    --或者通过查询语句把原编数据显示出来楼上的两种方法我试过,貌似不可以
      

  4.   

    我还真的试了啊。;with tmp
    as
    (select rn=row_number()over(partition by b order by id),
    *
    from test)
    update tmp
    set a=rnselect *from test
    /*
    结果:
    id a b
    1 1 A
    2 1 B
    3 2 B
    4 2 A
    5 3 B
    */
    go
      

  5.   

    update t
    set a=(select count(*) from test where b=t.b and id<=t.id)
    from test t
    select count(*) from test  where b='A' and id<=1   这个为1select count(*) from test  where b='B' and id<=2   这个为1select count(*) from test  where b='B' and id<=3   这个为2select count(*) from test  where b='A' and id<=4   这个为2select count(*) from test  where b='B' and id<=5   这个为3应该是这样修改的吧!再次感谢了!
      

  6.   

    楼主这样查询
    select ID,
           a=(select count(*) from test where b=t.b and id<=t.id),
           b
    from test t
    order by b,a
    这里a是子查询得到的
    你可以看看子查询方的