完全对您所提供的数据基础,在这里做的一种方式:
with products as (select 'x' Item_id, 'B123' Product_Holder, 10 Price, 2 Mnth from dual union all
select 'x' Item_id, 'Z555' Product_Holder, 8 Price, 3 Mnth from dual union all
select 'y' Item_id, 'A444' Product_Holder, 15 Price, 2 Mnth from dual union all
select 'y' Item_id, 'K000' Product_Holder, 10 Price, 3 Mnth from dual),
sales as (select 'x' item_id, 'B123' issued_from, 'Z555' sent_to, null impact_value, 3 mnth from dual union all
select 'y' item_id, 'A444' issued_from, 'K000' sent_to, null impact_value, 3 mnth from dual)
select sls.item_id,
sls.issued_from,
sls.sent_to,
sum(case when prd.product_holder = issued_from then -1 * prd.price
else prd.price
end) impact_value,
sls.mnth
from products prd
inner join sales sls on (prd.item_id = sls.item_id
and (prd.product_holder = sls.issued_from
or (prd.product_holder = sls.sent_to
and prd.mnth = sls.mnth)))
group by sls.item_id,
sls.issued_from,
sls.sent_to,
sls.mnth;
ITEM_ID ISSUED_FROM SENT_TO IMPACT_VALUE MNTH
------- ----------- ------- ------------ ----------
y A444 K000 -5 3
x B123 Z555 -2 3
并更新销售表,我会做:
merge into sales tgt
using (select sls.item_id,
sls.issued_from,
sls.sent_to,
sum(case when prd.product_holder = issued_from then -1 * prd.price
else prd.price
end) impact_value,
sls.mnth
from products prd
inner join sales sls on (prd.item_id = sls.item_id
and (prd.product_holder = sls.issued_from
or (prd.product_holder = sls.sent_to
and prd.mnth = sls.mnth)))
group by sls.item_id,
sls.issued_from,
sls.sent_to,
sls.mnth) src
on (tgt.item_id = src.item_id
and tgt.issued_from = src.issued_from
and tgt.sent_to = src.sent_to
and tgt.mnth = src.month) -- assuming these columns are enough to define a unique row in the sales table
when matched then
update set tgt.impact_value = src.impact_value;
注:您可能需要计算销售表中指定的月份之前或之前的最新issued_from行,但这是一个练习,由您决定。
我也希望在您的真实表格中,您有更好的销售日期标识符,而不仅仅是一个月的数字。例如。月份和年份,甚至更好,实际的日期!
我正在使用Oracle – bytebiscuit
这些组合是否总是成对出现?如果在月份= 4时item_id'y'有另一行? –
是的,Damine,你是对的! – bytebiscuit