在SQL Pivot中将NULL转换为0

时间:2013-04-05 05:01:46

标签: sql sql-server pivot

以下代码成功生成了一个Pivot(显示在代码下方)

select * 
from (
Select GLAccount , DC , Amount  from AccountingTxns a where Acctno = '178523'
)
TableData
pivot (
sum (Amount)
for DC in ([D],[C])
) 
as SumAmountDC
GLAccount             D       C
InterestDue     3801.37 3731.68
Cash            25600   25000
IntReceivable   3801.37 3801.37
IntIncome       NULL    3684.47
IntOverdue      NULL    116.9
Principal      25000    21868.32

如何摆脱NULL(即将它们转换为0)?

1 个答案:

答案 0 :(得分:2)

使用COALESCE

SELECT  GLAccount, 
        COALESCE(D, 0) D, 
        COALESCE(C, 0) C
FROM 
        (
            SELECT  GLAccount, 
                    DC , 
                    Amount  
            FROM    AccountingTxns a 
            WHERE   Acctno = '178523'
        ) TableData
        PIVOT
        (
            SUM(Amount)
            FOR DC IN ([D],[C])
        ) SumAmountDC