数据库中记录是这样的
=========
Code   OrderNo
1001     1
1001     3
1001     4
2001     2
2001     3
2001     4=========orderno为code组内顺序号
由于对于某个code值 orderno 可能出现间断,不连续
所以现在需要将orderno重新排序,使之连续
排序后结果为:=========
Code   OrderNo
1001     1
1001     2
1001     3
2001     1
2001     2
2001     3
=========
本来是在程序中遍历数据集实现的
但是后来发现,一旦数据量增多,执行会变得其慢!
所以用sql语句实现的时候也不能用游标
请问,这样的要求能用sql语句实现吗?
有热心人最好能写成通用的sql语句
当然能在sqlserver中通过也可以
因为我的sql也要用在ACCESS数据库中(比如declare,case等access就不支持了)
万分感谢^_^

解决方案 »

  1.   

    create table T(Code int, OrderNo int)
    insert T select 1001,     1
    union all select  1001,    3
    union all select 1001,     4
    union all select 2001,     2
    union all select  2001,     3
    union all select 2001,     4select Code, OrderNo=(select count(*) from T where Code=A.Code and OrderNo<=A.OrderNo) from T as A--result
    Code        OrderNo     
    ----------- ----------- 
    1001        1
    1001        2
    1001        3
    2001        1
    2001        2
    2001        3(6 row(s) affected)
      

  2.   

    declare @a table(code int,orderno int)
    insert into @a select 1001,1 union all
    select 1001,3 union all
    select 1001,4 union all
    select 2001,2 union all
    select 2001,3 union all
    select 2001,4
    select code,oederno=(select count(distinct orderno) from @a a where b.orderno>=a.orderno and b.code=a.code) from @a b
    result:
    code        oederno     
    ----------- ----------- 
    1001        1
    1001        2
    1001        3
    2001        1
    2001        2
    2001        3(所影响的行数为 6 行)
      

  3.   

    晕哦,按第一位老兄的方法
    在access中查询出来order的值竟然都是-1
      

  4.   

    --环境
    create table tab
    (
    code int,
    orderno int
    )insert into tab select 1001,     1
    insert into tab select 1001,     3
    insert into tab select 1001,     4
    insert into tab select 2001,     2
    insert into tab select 2001,     3
    insert into tab select 2001,     4--更新语句
    update a
    set orderno = (select count(1) from tab where code = a.code and orderno <= a.orderno)
    from tab a--查询
    select * from tab--结果
    1001 1
    1001 2
    1001 3
    2001 1
    2001 2
    2001 3--删除环境
    drop table tab
      

  5.   

    lzy6204(为了忘却的记忆) ( ) 信誉:101    Blog  2007-01-11 10:27:41  得分: 0  
     
     
       晕哦,按第一位老兄的方法
    在access中查询出来order的值竟然都是-1
      
     
    ------------
    我的SQL語句是在SQL2000在執行的, 不是ACCESS
      

  6.   

    marco08(天道酬勤) ( ) 信誉:100    Blog  2007-01-11 10:33:36  得分: 0  
     
     
       lzy6204(为了忘却的记忆) ( ) 信誉:101    Blog  2007-01-11 10:27:41  得分: 0  
     
     
       晕哦,按第一位老兄的方法
    在access中查询出来order的值竟然都是-1
      
     
    ------------
    我的SQL語句是在SQL2000在執行的, 不是ACCESS
      
     
    ============
    是的,各位的方法在sql2000执行都正确,但是在access中执行都不能通过
    看来得另想办法了,谢谢各位的热心帮助
    结贴了^_^