LedgerId AccountId EntryType Debit Credit
2 2 D 50000.00 NULL
3 2 D 10000.00 NULL
4 2 C NULL 25000.00
6 2 C NULL 10000.00
7 2 D 89000.00 NULL
8 2 D 89000.00 NULL
10 3 D 715871.00 NULL
以下查询计算
Balance
:Select Accounts.ID [AccountID],Name,AccountType [AccountType], SUM(Debit) - SUM(Credit) [Balance] FROM Accounts
join Dealers on Accounts.DealerId = Dealers.ID
join Ledger on Accounts.ID = Ledger.AccountId
GROUP BY Accounts.ID, Name, AccountType
它返回:
AccountID Name AccountType Balance
2 Mateen P 203000.00
3 Shery P NULL
预期输出:
AccountID Name AccountType Balance
2 Mateen P 203000.00
3 Shery P 715871.00
Balance
如果帐户 3 为空,则返回 null
当涉及到从 null
中减去任何内容时.例如:
select 5 - NULL
返回
NULL
.问题:现在,我怎样才能获得
Balance
而不是 NULL
?
最佳答案
您可以使用 coalesce
:
coalesce(sum(Debit), 0) - coalesce(sum(Credit), 0)
关于sql - 对 null 的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31554998/