可能重复:
Oracle: Updating a table column using ROWNUM in conjunction with ORDER BY clause
我有一个返回一组有序记录的查询,我想将结果集中每行的rownumber复制到记录本身的一个名为Sequence的特定字段中。
SELECT ROWNUM, ID
FROM (
SELECT ID
FROM MYTABLE
WHERE PARENT = 1
ORDER BY SEQUENCE ASC
)
我有每行的ID,以及我要放在rownum
字段中的SEQUENCE
。如何循环遍历此结果集并相应地更新表?
答案 0 :(得分:2)
merge into mytable t
using (SELECT ROWNUM rn, ID
FROM (
SELECT ID
FROM MYTABLE
WHERE PARENT = 1
ORDER BY SEQUENCE ASC
)) S
on (t.id=s.id)
when matched then update set
t.sequence=s.rn
如果id不是唯一的,您可以肯定:
merge into mytable t
using (SELECT ROWNUM rn, rwd
FROM (
SELECT rowid rwd
FROM MYTABLE
WHERE PARENT = 1
ORDER BY SEQUENCE ASC
)) S
on (t.rowid=s.rwd)
when matched then update set
t.sequence=s.rn
答案 1 :(得分:1)
请尝试:
merge into EMP_MASTER x
using (
SELECT ID, ROW_NUMBER() OVER(ORDER BY SEQUENCE) y
FROM MYTABLE
WHERE PARENT = 1
) s on (s.ID=x.ID)
when matched then update set
x.sequence=s.y;
适用于唯一ID。