如何获得标量平衡

时间:2020-06-14 19:06:28

标签: sqlite

要计算起始分类帐余额,请执行以下查询:

select
    case when DrControl = 7 then sum(Amount) end Debit,
    case when CrControl = 7 then sum(Amount) end Credit
from Transactions
where 7 in (DrControl, CrControl)
and Date < '2020-05-31'
group BY DrControl --, CrControl

,它返回两行:

Debit       Credit
------------------
900000      NULL
NULL        40000

我必须通过在我的应用程序代码中相互减去一个来计算余额。在这种情况下,我真正需要的是借方-贷方(900000-40000)=860000。

1 个答案:

答案 0 :(得分:0)

您不需要group by ...,只需要条件聚合:

select
    sum(case when DrControl = 7 then Amount end) -
    sum(case when CrControl = 7 then Amount end) 
from Transactions
where 7 in (DrControl, CrControl) and Date < '2020-05-31'

只要没有DrControl = 7CrControl = 7的行,也使用COALESCE()返回0而不是null

select
    coalesce(sum(case when DrControl = 7 then Amount end), 0) -
    coalesce(sum(case when CrControl = 7 then Amount end), 0) 
from Transactions
where 7 in (DrControl, CrControl) and Date < '2020-05-31'