pivot将null转换为零

时间:2016-02-09 06:52:14

标签: sql sql-server common-table-expression

下面我创建了一个2表transaction_type和transaction_master TRANSACTION_TYPE。 transaction_type包含信用卡和借记卡ID 那么transaction_type包含交易细节

   transaction_type
   -----------------
   transaction-id|transaction-name
   1             |credit 
   2             |debit

   transaction_master
   -----------
   transaction-id|date_of_transaction|amount
   1             |2016-01-12         |100  
   2             |2015-12-30         |200
   1             |2016-01-05         |300   
   1             |2015-12-04         |500 
   2             |2015-12-12         |50  
   2             |2015-12-25         |1000    
   1             |2016-01-30         |100    

   normal PIVOT output is
   -----------------------
   YEAR|Jan |Feb |mar |Apr |may |Jun |Jul |Aug |Sep |Oct |Nov |Dec

   2015|null|null|null|null|null|null|null|null|null|null|null|-700

   2016|500 |null|null|null|null|null|null|null|null|null|null|null


   But i want this
   YEAR|Jan |Feb |mar |Apr |may |Jun |Jul |Aug |Sep |Oct |Nov |Dec

   2015|0   |0   |0   |0   |0   |0   |0   |0   |0   |0   |0   |0   

   2016|500 |0   |0   |0   |0   |0   |0   |0   |0   |0   |0   |0  

以上“NULL”和“否定”值应为“0”

   with AA as(select year(d.date_of_transaction),left(date name(month,date_of_transaction),3) as month,sum (case when c. transaction_type like '%c%' then d.Amount else d.Amount*-1)as balance
 from transaction_master d join on transaction_type c c.transaction-id=d.transaction-id group by date_of_transaction) select * from AA pivot(sum(balance) for [month] in (Jan,Feb,Mar,Apr,May,jun,Jul,Aug,Sep,Oct,Nov,Dec)) as pvt

2 个答案:

答案 0 :(得分:2)

您可以在以下内容中使用CASEISNULL

with aa as(select year(d.date_of_transaction), 
                  case when isnull(left(datename(month,date_of_transaction),3),0) < 1 then 0 else left(datename(month,date_of_transaction),3) end as month 

答案 1 :(得分:1)

您可以在最终的SELECT条款中使用ISNULL

  

[ISNULL]用指定的替换值替换NULL。

;with AA as(
    select 
        year(d.date_of_transaction) AS [year],
        left(datename(month,date_of_transaction),3) as [month],
        sum (case when c. transaction_type like '%c%' then d.Amount else d.Amount*-1 end)as balance
    from 
        transaction_master d join transaction_type c on c.[transaction-id]=d.[transaction-id]
    group by 
        date_of_transaction
 ) 
 select 
    [year],ISNULL(Jan,0) Jan,ISNULL(Feb,0) Feb,ISNULL(Mar,0) Mar,ISNULL(Apr,0) Apr,ISNULL(May,0) May,ISNULL(jun,0) jun,ISNULL(Jul,0) Jul,ISNULL(Aug,0) Aug,ISNULL(Sep,0) Sep,ISNULL(Oct,0) Oct,ISNULL(Nov,0) Nov,ISNULL([Dec],0) [Dec]
 from 
    AA 
    pivot(sum(balance) for [month] in (Jan,Feb,Mar,Apr,May,jun,Jul,Aug,Sep,Oct,Nov,Dec)) as pvt