2015-07-22 196 views
3
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

回答

3

您可以使用coalesce

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

最新的DIFF B/w'isnull'和'coalesce'? – Shaharyar

+1

@Shaharyar:[這裏是一篇很好的文章](http://sqlmag.com/t-sql/coalesce-vs-isnull) – potashin

1

嘗試這與使用ISNULL的(數值,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 
0

問題具有NULL值,SUM聚合函數忽略NULL值。 如果找到NULL值,合併函數將用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 
+0

我認爲我的方案無論是在'SUM'之前檢查'NULL'還是沒有區別在SUM之後。可以? – Shaharyar

0

兩種聚結()和ISNULL()函數使用來檢查空值

ISNULL(@變量,0)
聚結(@變量,0)