2014-02-12 54 views
4

我用下面的減去兩柱空

select TotalCredits - TotalDebits as Difference 
from 
(
select 
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits, 
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits 
) temp 

這將返回一個字段與我的區別,我存在的問題是,如果表中有沒有信用,但借貸,臨時表中包含一個TotalCredits字段中的NULL值禁止數學完成。 (Vica Versa on Credits但不支付)我已經嘗試過Coalese,但似乎無法使其工作。

合理我需要檢查:

sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1 as TotalCredits is 
null then totalcredits = 0 and visa versa 

SQL Server 2008中

+4

你不能用0代替'NULL'值? 'SELECT ISNULL(SUM(TotalAmount),0)FROM journal WHERE memberid = 48 AND Credit = 1'? – SchmitzIT

+0

信用= 1的標準可能不會產生任何行,所以我不能將數據設置爲零,如果沒有行符合條件 – gbb116

回答

4
select ISNULL(TotalCredits,0) - ISNULL(TotalDebits,0) as Difference 
from 
(
select 
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits, 
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits 
) temp 
+0

這也似乎工作,謝謝傢伙!其他的只是更簡潔而沒有將0設置爲0 – gbb116

+0

您的我的答案選擇現在,即使沒有行也存在您的工作 – gbb116

+0

也感謝@SchmitzIT。 –

3

更改您的查詢條件的聚集,它解決了這個問題:

select sum(case when credit = 1 then TotalAmount else -TotalAmount end) as Difference 
from Journal 
where memberid = 48 and (credit = 1 or debit = 1); 

編輯:

如果您的信用卡和借記卡可能均爲1,請使用:

select (sum(case when credit = 1 then TotalAmount else 0 end) - 
     sum(case when debit = 1 then TotalAmount else 0 end) 
     ) as Difference 
from Journal 
where memberid = 48 and (credit = 1 or debit = 1); 
+0

這正是我所需要的,似乎是雙方都工作,謝謝戈登! – gbb116

+0

一些附帶案例需要警惕:如果Credit = 1和Debit = 1會怎樣?如果沒有行,其中memberid = 48會怎麼樣? –

+0

philip你剛剛讀過我的想法,我測試瞭如果根本沒有行存在,@guy的方法更好,如果沒有記錄存在,它仍然會返回0的金額,至於借方和貸方都選中,這隻會是一個編程錯誤,因爲它的一個或另一個。 – gbb116

0

使用ISNULL 0更換空,然後使之querys,然後總減法

0

哎喲創建一個子查詢。那個查詢讓我頭痛。 Discriminant functions是你的朋友,case可以讓你在SQL中輕鬆創建它們。只需簡單說明問題。

select total_credits = sum(case j.credit when 1 then 1 else 0 end) , 
     total_debits = sum(case j.debit when 1 then 1 else 0 end) , 
     total_delta = sum(case j.credit when 1 then 1 else 0 end) 
        - sum(case j.debit when 1 then 1 else 0 end) 
from journal j 
where j.memberid = 48 
1

你好可能是這樣也可以可以給預期的結果

select COALESCE(TotalCredits,0) - COALESCE(TotalDebits,0) as Difference 
from 
(
select 
(select sum(TOTALAMOUNT) from journal where memberid=48 and CREDIT =1) as TotalCredits, 
(select SUM(totalamount) from Journal where MEMBERID=48 and DEBIT =1) As TotalDebits 
) temp