我有以下方式的数据:
ORDER_NO FULFILL_ID SOURCE_LOC ITEM
100 11001 0021
100 11001 0031
100 12001 0014
100 13001 0053
每当source_loc相同时,它应该给出相同的fulfill_id。 ID应从1开始并递增1 ..因此数据应更新为
ORDER_NO FULFILL_ID SOURCE_LOC ITEM
100 1 11001 0021
100 1 11001 0031
100 2 12001 0014
100 3 13001 0053
如何更新列?
答案 0 :(得分:3)
这可以使用单个MERGE语句完成:
merge into orders o
using
(
select order_no,
dense_rank() over (order by source_loc) as rn,
source_loc,
item
from orders
) t on (o.order_no = t.order_no and o.item = t.item and o.source_loc = t.source_loc)
when matched then update
set fullfill_id = rn;
问题是:如果可以在运行时轻松计算,为什么需要保存此信息。
您可以创建如下视图:
create or replace view orders_2
as
select order_no,
dense_rank() over (order by source_loc) as fullfill_id,
source_loc,
item
from orders
答案 1 :(得分:0)
我不知道这是否重要,但是如果新记录带有相同的{% extends "base.html" %}
{% load render_table from django_tables2 %}
{% load crispy_forms_tags %}
{% block my_table %}
<div>
<form action="" method="get">
{% crispy filter.form filter.form.helper %}
</form>
</div>
{% render_table table %}
{% endblock %}
字段,并且您希望确保它们保留并继承先前为source_loc
分配的值,那么像这样可能会确保先前的ID被继承并分配新的ID:
fulfill_id
以这种方式,一旦将fulfill_id分配给source_loc,它就会被保留。像这样开始的数据:
update mytable t1
set t1.fulfill_id = (
with already as (
select distinct source_loc, fulfill_id
from mytable
where fulfill_id is not null
),
final_id as (
select distinct
m.source_loc,
coalesce (a.fulfill_id, dense_rank() over (order by m.source_loc)) as fulfill_id
from
mytable m,
already a
where
m.source_loc = a.source_loc (+)
)
select
f.fulfill_id
from final_id f
where
f.source_loc = t1.source_loc
)
where t1.fulfill_id is null;
会这样结束:
ORDER_NO FULFILL_ID SOURCE_LOC ITEM
100 1 11001 0021
100 1 11001 0031
100 2 12001 0014
100 3 13001 0053
100 12001 0014
100 10001 0014