我想根据A字段排序更新A字段update TEST set A = rownum
写成这样都可以
update TEST set A = rownum order by A
但是要是写成这样就不行了 ,~
有什么办法可以实现这样的效果吗 ?~
写成这样都可以
update TEST set A = rownum order by A
但是要是写成这样就不行了 ,~
有什么办法可以实现这样的效果吗 ?~
调试欢乐多
----
14 0
12 4
8 2
2 2
44 9
23 8想根据A的更新A的排序成ID A
----
14 0
8 1
2 2
12 3
23 4
44 5
as
(select 14 a,0 b from dual
union all
select 12,4 from dual
union all
select 8,2 from dual
union all
select 2,2 from dual
union all
select 44,9 from dual
union all
select 23,8 from dual
)
select a,b,row_number()over(order by b)-1 rn from a--RESULT:
14 0 0
8 2 1
2 2 2
12 4 3
23 8 4
44 9 5
--如果要更新,ID是主键的话:
--a 是表 b,c 表的别名
update a b set a=(select row_number()over(order by b)-1 from a c
where c.id=b.id) where exists(select 1 from a c where c.id=b.id)
这种就不要想了,你会造成二义性的。一边在更新一边还要按这个排序,冲突的。
直接的update写不出来,可以使用变通的方法实现,比如建个新表生成你要的数据,再rename什么的。
--如果ID是唯一,又不怎么清楚分析函数的话,可以用如下的方法更新
create table tb (id int , A int); --建表
--插入数据
insert into tb select 14,0 from dual union all
select 12,4 from dual union all
select 8,2 from dual union all
select 2,2 from dual union all
select 44,9 from dual union all
select 23,8 from dual ;
commit;--以下是SQL,注意ID如果是唯一的,不然要找一个唯一的组合条件。
update tb t
set t.a = (select rn
from (select k.*, rownum - 1 rn
from (select * from tb order by a) k) tp
where tp.id = t.id)
--备注,其实后面还应该加WHERE,,不过考虑到大多数都要全部更新,所以就不加了,工作忙
2 union all
3 select 12,4 from dual
4 union all
5 select 8,2 from dual
6 union all
7 select 2,2 from dual
8 union all
9 select 44,9 from dual
10 union all
11 select 23,8 from dual
12 /已创建6行。
SQL> edi
已写入 file afiedt.buf 1 update test1 a set num=(select rn from
2* (select id,row_number() over(order by num)-1 rn from test1) b where a.id=b.id)
SQL> /已更新6行。SQL> select * from test1; ID NUM
---------- ----------
14 0
12 1
8 5
2 3
44 4
23 2已选择6行。
已写入 file afiedt.buf 1 update test1 a set num=(select rn from
2* (select id,row_number() over(order by num,rowid)-1 rn from test1) b where a.id=b.id)
SQL> /已更新6行。
SQL> select * from test1 order by num; ID NUM
---------- ----------
14 0
8 1
2 2
12 3
23 4
44 5已选择6行。