Sql 计算余额金额并插入另一个表

Sql 计算余额金额并插入另一个表,sql,oracle,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 ACCO

我需要一些关于构建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'

可以使用条件聚合执行此操作:

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
将其插入到另一个表中,尽管我不确定单行中的单个值如何有用。

可以使用交叉应用

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'