特定条件的更新顺序-Oracle

时间:2019-06-02 20:55:38

标签: sql oracle

我有一张桌子:

表1

u_a_id      element_id       my_seq
1           HI01-01          1
1           HI01-02          1
1           HI02-01          1
1           HI02-02          1
1           HI02-03          1
1           HI02-04          1

2           HI01-01          1
2           HI01-02          1
2           HI02-01          1
2           HI02-02          1
2           HI02-03          1
2           HI02-04          1
2           HI03-02          1
2           HI03-03          1
2           HI05-04          1
2           HI05-05          1

如果每个u_a_id的HI 01 中的计数器更改为HI 02 ,我需要更新my_seq

输出如下:

u_a_id      element_id       my_seq
1           HI01-01          1
1           HI01-02          1
1           HI02-01          2
1           HI02-02          2
1           HI02-03          2
1           HI02-04          2

2           HI01-01          1
2           HI01-02          1
2           HI02-01          2
2           HI02-02          2
2           HI02-03          2
2           HI02-04          2
2           HI03-02          3
2           HI03-03          3
2           HI05-04          4
2           HI05-05          4

Oracle SQL中是否有一种方法可以实现这一目标?

2 个答案:

答案 0 :(得分:2)

为什么不只使用substr()

select t.*, to_number(substr(element_id, 3, 2)) as my_seq
from t;

第二种方法是使用dense_rank()

select t.*,
       dense_rank() over (partition by u_a_id order by substr(element_id, 1, 4)) as my_seq
from t;

如果要实际更新数据,可以使用merge

merge into t using
      (select t.*,
              dense_rank() over (partition by u_a_id order by substr(element_id, 1, 4)) as new_my_seq
       from t
      ) s
      on s.u_a_id = t.u_a_id and s.element_id = st.element_id
when matched then update
    set t.my_seq = s.new_my_seq;

答案 1 :(得分:0)

以下代码将为您提供所需的确切信息:

Take Heap Snapshot

输出:

select u_a_id, 
element_id, 
dense_rank() over (order by substr(element_id,1,4)) as my_seq
from tab1 
order by u_a_id,element_id;