如何计算案例的差异

时间:2017-02-20 08:54:07

标签: sql sql-server-2008

我有类似的东西

CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'd' THEN SecDebit END AS 'debit',
CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'c' THEN SecCredit END AS 'credit',

我想计算借方和贷方之间的差异

如果我正在使用

Bal=CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'd' THEN SecDebit END  - CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'c' THEN SecCredit END,

它给了我空值,在这个陈述中有什么不对,任何人都可以建议在这里做什么。

3 个答案:

答案 0 :(得分:1)

对NULL执行任何算术都会返回NULL。当条件不匹配时,使每个案例返回0而不是NULL:

GROUP BY

答案 1 :(得分:0)

如果您只有一列(CreditOrDebit)来区分信用卡或借记卡,那么就不需要有两列secDebit和secCredit。所以我假设只有一列secDebitorCredit。考虑到以下情况,查询将为您提供借方 - 贷方之间的最终差异。

SELECT SUM(ISNULL(CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'd' THEN secDebitorCredit END , 0)  - 
ISNULL(CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'c' THEN secDebitorCredit END, 0) )AS 'Diff'

答案 2 :(得分:-1)

Bal=(CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'd' THEN SecDebit ELSE 0 END - 
CASE WHEN j.DocTypeID=0 AND CreditOrDebit = 'c' THEN SecCredit ELSE 0 END)