![](/img/trans.png)
[英]Oracle procedure to update values of one table to another another table field
[英]Update one field in a table in reference to another field on the same table Oracle
我需要参考同一张表上的另一个字段Entity_id,使用顺序值(例如001、002、002)更新varchar2字段。 我需要它,例如,如果我在两个不同的行上具有相同的entity_id,则顺序值应相同。
输出示例:
Entity_id Seq_field
1234 001
1234 001
4567 002
4567 002
3412 003
我尝试使用rownum,但是它为每个entity_id提供了不同的值,当然这些值没有尾随零。 请帮忙。
merge into the_table
using
(
select rowid as rid,
entity_id,
to_char(dense_rank() over (order by entity_id), 'FM00000') as seq
from foo
) t on (the_table.rowid = t.rid)
when matched
then update set seq_field = t.seq;
如果要为每个entity_id
开始一个新序列, entity_id
需要稍微更改一下语句:
merge into foo
using
(
select rowid as rid,
entity_id,
to_char(row_number() over (partition by entity_id order by null), 'FM00000') as seq
from foo
) t on (foo.rowid = t.rid)
when matched
then update set seq_field = t.seq;
请注意,我使用row_number()
而不是dense_rank()
并按partition by entity_id
进行partition by entity_id
以每个新的entity_id
值重新开始编号。 如果你有另一列,将确定的“秩序”一个ENTITY_ID,那么你就可以更换null
在order by null
与该列如order by created_at
您有几条记录? 以下是我想出的一个解决方案,但不能与大量数据配合使用。
CREATE TABLE tab (entity_id NUMBER, seq_field VARCHAR2(3));
INSERT INTO tab VALUES (1234, NULL);
INSERT INTO tab VALUES (1234, NULL);
INSERT INTO tab VALUES (4567, NULL);
INSERT INTO tab VALUES (4567, NULL);
INSERT INTO tab VALUES (3412, NULL);
UPDATE tab t SET seq_field = (
SELECT LPAD(rnk, 3, '0')
FROM (
SELECT entity_id, seq_field, DENSE_RANK() OVER (ORDER BY entity_id) AS rnk
FROM tab
) t2
WHERE t2.entity_id = t.entity_id AND rownum = 1
);
检查SQLFiddle: http ://sqlfiddle.com/#!4/3959d/1
考虑将SQL
和ORACLE
标记都添加到您的问题中,猜想您会得到更多关注,并且可能是一个更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.