【问题标题】:How to calculate Total transactions amount column with input / output type?如何计算输入/输出类型的总交易金额列?
【发布时间】:2021-06-25 15:41:10
【问题描述】:

我有两张表:(交易和账户)它们的列如下图所示:

Accounts 表很简单,只有两列 ID 和帐户名称。

Transactions 表中的重要列是 Amount 和 type,type 表示该交易是对帐户的输入还是输出。

我想用 SQL 查找每个帐户的当前总金额(输入 - 输出)

这是我尝试过的,但我无法更进一步:

select c.TRS_AC_ID, CompAccount, sum(Amount), Type from Accounts c 
INNER JOIN Transactions t on c.TRS_AC_ID = t.TRS_AC_ID GROUP by CompAccount, Type

【问题讨论】:

  • 只标记您使用的数据库。

标签: sql select


【解决方案1】:

您可以使用case 表达式按原样返回“输入”事务并将“输出”事务作为负数返回,而不是按type 分组:

SELECT   c.TRS_AC_ID, CompAccount, SUM(CASE type WHEN 'O' THEN -1 * amount ELSE amount END)
FROM     Accounts c 
JOIN     Transactions t on c.TRS_AC_ID = t.TRS_AC_ID
GROUP BY c.TRS_AC_ID, CompAccount

【讨论】:

    【解决方案2】:

    您可以使用以下 SQL 来获取输入输出的结果,但是,如果您需要单独的结果,那么您也可以使用任一子查询。

    select
        (select sum(amount) as input from transaction
        where trs_ac_id = '1' and type_io = 'I'))
        -
        (seelect sum(amount) as output from transaction
        where trs_ac_id = '2' and type_io = 'O')) as current_tot_amt
    from dual;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多