Sql PIVOT,如何使用PIVOT将NULL转换为结果中的值0

时间:2017-11-04 11:19:40

标签: sql sql-server pivot pivot-table

这是使用

的查询
select * from ( select * from  ( select (Left(CONVERT(date, T_Canteen.vcBillDate, 103),10)) as BillDate ,
ISNULL( SUM( T_CanteenPayment.dPayAmt),0 )as dPayAmt , case ISNULL ( T_CanteenPayment.iPayMode, 0.00) when 15 then 'Cash'
 when 17 then  'eWallet' when 19 then 'Card'  end  as Paymode
 from T_CanteenPayment
inner join T_Canteen on T_Canteen.iKey = T_CanteenPayment.iTransKey 
inner join M_CAN_Outlet on T_Canteen.iOutletKey = M_CAN_Outlet.iKey 
left join   M_Gn_Desk ON M_CAN_Outlet.iDeskKey = M_Gn_Desk.iKey   WHERE T_Canteen.iDelFlg =0 and T_Canteen.iSoftKey  = 42
 and (right(CONVERT(date,T_CanteenPayment.dtPayDt, 103),10))between(right(CONVERT(date,'01/09/2017', 103),10))      
and (right(CONVERT(date,'04/11/2017', 103),10))group by (Left(CONVERT(date, T_Canteen.vcBillDate, 103),10)), T_CanteenPayment.iPayMode , M_CAN_Outlet.vcName  )
 as s 
 PIVOT    
(    
    max ( dPayAmt)
    FOR [Paymode] IN (Cash,  eWallet,Sodexo_Card)    
)AS pvt )as GH 

**我得到了输出**

BillDate    Cash    eWallet Sodexo_Card
----------------------------------------------------
2017-09-01  NULL    110.00  NULL
2017-09-02  NULL    50.00   NULL
2017-09-05  50.00   NULL    NULL
2017-09-06  32.00   3.00    NULL
2017-09-07  28.00   3.00    NULL
2017-09-08  NULL    785.00  NULL

如何在结果中将NULL转换为值0。请帮忙整理出来

2 个答案:

答案 0 :(得分:0)

您可以指定列而不是使用isnull()并使用coalesce()(或select BillDate , Cash = isnull(Cash,0) , eWallet = isnull(eWallet,0) , Sodexo_Card = isnull(Sodexo_Card,0) from (.... ):

require_relative "photo_uploader"

class Photo
  include DataMapper::Resource

  property :id, Serial
  property :title, String
  belongs_to :property
  mount_uploader :source, PhotoUploader
end

答案 1 :(得分:0)

您的查询将更简单,因为条件聚合:

awk: record `,1402786,535,1,47432... has too many fields record number 1`

注意:

  • 不需要子查询。
  • 使用日期的标准格式可简化代码并使其更具可读性。
  • 表别名使代码更易于编写和阅读。
  • select convert(date, c.vcBillDate) as BillDate , sum(case when cp.iPayMode = 15 then cp.dPayAmt else 0 end) as as cash, sum(case when cp.iPayMode = 17 then cp.dPayAmt else 0 end) as as eWalet, sum(case when cp.iPayMode = 19 then cp.dPayAmt else 0 end) as as card from T_CanteenPayment cp inner join T_Canteen c on c.iKey = cp.iTransKey inner join M_CAN_Outlet o on c.iOutletKey = o.iKey left join M_Gn_Desk d on o.iDeskKey = d.iKey where c.iDelFlg = 0 and c.iSoftKey = 42 and convert(date, cp.dtPayDt >= '2017-09-01' and '2017-11-04' group by convert(date, c.vcBillDate) order by convert(date, c.vcBillDate); 未使用,因此应从查询中删除。