2014-02-12 53 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