对null的算术运算

时间:2015-07-22 06:00:18

标签: sql sql-server conditional-statements

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

帐户3的Balance为空,在从null中减去任何内容时返回null

例如:

select 5 - NULL

返回NULL

问题:现在,如何获取Balance代替NULL

4 个答案:

答案 0 :(得分:4)

您可以使用coalesce

coalesce(sum(Debit), 0) - coalesce(sum(Credit), 0)

答案 1 :(得分:2)

尝试使用isnull(value,0),它将空值取为0

Select Accounts.ID [AccountID],Name,AccountType [AccountType], 
 SUM(isnull( Debit,0)) - SUM(isnull(Credit,0)) isnull([Balance],0) as 
   Balance FROM Accounts 
     join Dealers on Accounts.DealerId = Dealers.ID 
     join Ledger on Accounts.ID = Ledger.AccountId
GROUP BY Accounts.ID, Name, AccountType

答案 2 :(得分:0)

NULL值问题,SUM聚合函数忽略NULL值。 如果找到NULL值,Coalesce函数将用0替换它。

    Select Accounts.ID [AccountID],
           Name,
           AccountType [AccountType], 
           SUM(coalesce(Debit,0)) - SUM(coalesce(Credit,0)) [Balance] 
FROM       Accounts 
           join Dealers on Accounts.DealerId = Dealers.ID 
           join Ledger on Accounts.ID = Ledger.AccountId
           GROUP BY Accounts.ID, Name, AccountType 

答案 3 :(得分:0)

Coalesce()和IsNULL()函数都用于检查空值

ISNULL(@变量,0)
聚结(@变量,0)