想要在贷方栏上显示计算的负余额,在借方栏上显示正值

Want to display Calculated Negative balance on Credit Side Column and Positive on Debit Side

我正在 Oracle Apex 中创建跟踪余额报告。

我有 table 格式如下:

Account_id     Title    DC    Amount
    10         Test     1     3000
    10         Test     2     5000
    20         XYZ      1     7000
    20         XYZ      2     2000

DC 列 = 1 平均借方和 2 平均贷方

我想如果总金额为负,则在没有负号的信用侧栏中显示净信用额。如果总金额为正,则在借方栏中显示净借方金额。喜欢

Account_id     Title    Debit    Credit
    10         Test              2000
    20         XYZ      5000

如何使用Sql查询?

谢谢

您也可以使用条件聚合。

select account_id, title,
       case when sum(case when DC = 1 then amount else -1*amount end) > 0 
            then sum(case when DC = 1 then amount else -1*amount end) 
       end debit,
       case when sum(case when DC = 2 then amount else -1*amount end) > 0 
            then sum(case when DC = 2 then amount else -1*amount end) 
       end credit
  from your_table t
 group by account_id, title

首先我在内联视图中计算余额,然后应用 group by 子句以获得所需的输出。

select ACCOUNT_ID, TITLE, case when BALANCE < 0 then abs(BALANCE) end Debit, case when BALANCE >= 0 then BALANCE end credit
from (
   select ACCOUNT_ID, TITLE, DC, AMOUNT
     , sum(case when DC = 1 then -1 * AMOUNT else AMOUNT end)over(partition by ACCOUNT_ID, 
            TITLE) balance
   from your_table
)
group by ACCOUNT_ID, TITLE, BALANCE
;