我有两个表是base_table,另一个是txn_table,如下所示
base_table
Person | Amount
----------------
P1 300
p2 200
p3 100
TXN_TABLE
Person | txn_type | Amount
---------------------------------
P1 Debit 200
P2 Credit 200
P3 Debit 100
P1 Credit 400
我需要基于 txn_table base_table base_table 诸如p1之类的数据已经完成了借记和信用,总计算类似于(信用debit)=(400-200))= 200,并且已经在 base_table 中已经有300好吧,请帮助我写 Oracle SQL QUERY
更新后的base_table中的数据应像这样。
base_table
Person | Amount
P1 500
p2 400
p3 0
注意:在这里我不应该使用plsql块,我只需要使用SQL查询执行此更新。
内联相关子查询可能会完成工作:
UPDATE base_table b
SET b.amount =
b.amount
+ NVL(
(SELECT SUM(DECODE(t.txn_type, 'Credit', 1, -1) * t.amount)
FROM txn_table t
WHERE t.person = b.person
), 0)
在Oracle中,从另一个更新一个表的典型方法是使用相关的子征服:
update base_table b
set amount = b.amount +
(select sum(case when t.txn_type = 'Credit' then t.amount else - t.amount end)
from txn_table t
where t.person = b.person
)
where exists (select 1
from txn_table t
where t.person = b.person
having sum(case when t.txn_type = 'Credit' then t.amount else - t.amount end) <> 0
);
只是建议另一种方法。
merge into base_table tt
using
( select person , sum( decode(upper(txn_type) ,
'CREDIT', + AMOUNT ,
'DEBIT', - AMOUNT
) ) as final
from Txn_table
group by person ) b
on ( tt.person = b.person )
when matched then
update set tt.AMOUNT = tt.AMOUNT + b.final