日期:2014-05-18  浏览次数:20487 次

【急】求一update Sql语句,解决马上结贴给分!谢谢
数据库中记录是这样的
=========
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就不支持了)
万分感谢^_^

------解决方案--------------------
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, 4

select 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)
------解决方案--------------------
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 行)
------解决方案--------------------
顶有分就先顶一下
------解决方案--------------------
呵呵,大家好快,楼上两位都正解
------解决方案--------------------
--环境
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
------解决方案--------------------
lzy6204(为了忘却的记忆) ( ) 信誉:101 Blog 2007-01-11 10:27:41 得分: 0


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


------------
我的SQL語句是在SQL2000在執行的, 不是ACCESS
------解决方案--------------------