简体   繁体   English

按行数更新Oracle SQL

[英]Oracle SQL Update by rownum

I have the data in the following format: 我有以下格式的数据:

ORD_NO  ITEM  FULFILL_ID
SA1     1000     1 
SA1     2000     2
SA2     2000     1
SA2     3000     2
SA2     9000     3

I want to fill in the values for the column FULFILL_ID, which should start with 1 and increase till the number of rows for one particular ORD NO, as I have filled above. 我想填写FULFILL_ID列的值,该值应从1开始并增加,直到一个特定的ORD NO的行数为止,就像我在上面填写的那样。

How to do it ? 怎么做 ?

This is what ROW_NUMBER() does: 这是ROW_NUMBER()作用:

select ord_no, item,
       row_number() over (partition by ord_no order by item) as fulfill_id
from table t;

This returns the value as a query. 这将返回值作为查询。 A slightly different query is needed for an update. 更新需要一个稍有不同的查询。

EDIT: 编辑:

The update can be done like this: 更新可以像这样完成:

update table t
    set fulfill_id = (select count(*)
                      from table t2
                      where t2.ord_no = t.order_no and
                            t2.item <= t.item
                     );

This version assumes that item is different for the same values of ord_no . 此版本假定item是相同的值不同ord_no

you can use merge statement for this 您可以为此使用合并语句

merge into table1 t3 using
(
select ord_no, item,
       row_number() over (partition by ord_no order by item) as fulfill_id
from table1 
) s
on 
(t3.ORD_NO=s.ORD_NO and t3.ITEM=s.ITEM)
when matched then
update set t3.FULFILL_ID=s.fulfill_id 

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

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