简体   繁体   English

使用基于同一表中varchar字段的序列号更新Oracle表列

[英]Update Oracle table column with a sequence number based on varchar field in same table

I am in need of help with the syntax to update an existing field in an oracle table with a new number sequence based on the ordering of another field that is VARCHAR2. 我需要有关语法的帮助,该语法根据另一个字段VARCHAR2的顺序使用新的数字序列更新oracle表中的现有字段。

Current Table: 当前表:

CODE    CODE_ORDER
A00     3
A00.0   4
A00.1   6
A00.9   8

Desired Outcome: 期望的结果:

CODE    CODE_ORDER
A00     1
A00.0   2
A00.1   3
A00.9   4

The SELECT statement here gives me the desired results, but when I use it with an UPDATE statement, I receive an error. 此处的SELECT语句为我提供了所需的结果,但是当我将它与UPDATE语句一起使用时,会收到错误消息。

UPDATE Table SET code_order = (select row_number() over (order by 
code asc) from Table)

The UPDATE statement displays this error: UPDATE语句显示此错误:

ORA-01427: single-row subquery returns more than one row

Thank you in advance for any suggestions. 预先感谢您的任何建议。

You could do this: 您可以这样做:

merge
into table
using (
  select code,row_number() over (order by code asc) as new_code_order from table
) new_table
on (table.code = new_table.code)
when matched then update set
  table.code_order = new_table.new_code_order

I think this would also work in this simple case: 我认为这在以下简单情况下也可以:

update (select * from table order by code) set code_order = rownum;

You need to use subquery in SET clause as following: 您需要在SET子句中使用子查询,如下所示:

UPDATE Table t SET t.code_order = (
Select tin1.rn from
(select row_number() over (order by tin.code asc) rn, tin.code from Table tin) tin1
Where t.code = tin1.code)

Note : thks query will work for sample data where there is no duplicate value exists in code column. 注意 :在代码列中不存在重复值的情况下,该查询将适用于示例数据。

Cheers!! 干杯!!

You can use with..as clause 您可以使用with..as子句

update tab t
   set code_order = ( with tb as ( 
                      select t.*,row_number() over (order by code) as rn from tab t
                    )  
                    select rn
                      from tb
                     where tb.code=t.code)

considering the values for code column is unique 考虑到code列的值是唯一的

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM