计算余额并插入另一张表

时间:2018-12-06 21:28:45

标签: sql oracle

我在构建sql查询时需要一些帮助,下面有两个查询,我想合并从贷方减去借方的总和,然后将结果作为余额插入到另一个表中

select sum(amount)
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='credit' and account_type='customer' and IS_DELETED='false' 

select sum(amount)
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME='55555' and transaction_type='debit' and account_type='customer' and IS_DELETED='false'

2 个答案:

答案 0 :(得分:0)

可以使用交叉申请

select a.*, b.CreditSum, c.DebitSum
from ACCOUNT_TRANSACTIONS a
cross apply
   (select sum(amount) as CreditSum
    from ACCOUNT_TRANSACTIONS
    where CUSTOMER_USER_NAME='55555' and transaction_type='credit' and account_type='customer' and IS_DELETED='false'
    ) b
cross apply
   (select sum(amount) as DebitSum
    from ACCOUNT_TRANSACTIONS
    where CUSTOMER_USER_NAME='55555' and transaction_type='debit' and account_type='customer' and IS_DELETED='false'
    ) c
where a.CUSTOMER_USER_NAME='55555' and a.account_type='customer' and a.IS_DELETED='false'

答案 1 :(得分:-1)

您可以使用条件聚合来做到这一点:

select sum(case when transaction_type = 'credit' then amount when transaction_type = 'debit' then - amount end) as balance
from ACCOUNT_TRANSACTIONS
where CUSTOMER_USER_NAME = '55555' and
      account_type = 'customer' and
      IS_DELETED = 'false' ;

然后您将使用insert将此表插入另一个表中,尽管我不确定单行中的单个值如何有用。