用Null减去两列

时间:2014-02-12 19:34:45

标签: sql sql-server

我使用以下

 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有积分,但没有借记)我曾尝试过coalese,但似乎无法让它发挥作用。

理性地我需要检查是否:

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

sql server 2008

5 个答案:

答案 0 :(得分:5)

 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

答案 1 :(得分: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); 

答案 2 :(得分: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

答案 3 :(得分:0)

使用isnull创建一个子查询,将null替换为0,然后进行求和查询,然后进行总减法

答案 4 :(得分: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