Sql PIVOT,如何使用 PIVOT 将结果中的 NULL 转换为值 0
Posted
技术标签:
【中文标题】Sql PIVOT,如何使用 PIVOT 将结果中的 NULL 转换为值 0【英文标题】:Sql PIVOT, How I convert the NULL to value 0 in the Result using PIVOT 【发布时间】:2017-11-04 11:19:40 【问题描述】:这是正在使用的查询
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。请帮忙解决
【问题讨论】:
将列包装在 ISNULL(列名,0)中。没有任何格式就很难阅读你的 SQL。 现在我格式化了查询 它的工作。非常感谢@DavidBeaumont 【参考方案1】:您可以指定列而不是使用select *
并使用isnull()
(或coalesce()
):
select
BillDate
, Cash = isnull(Cash,0)
, eWallet = isnull(eWallet,0)
, Sodexo_Card = isnull(Sodexo_Card,0)
from (....
【讨论】:
【参考方案2】:您的查询会像条件聚合一样简单:
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);
注意事项:
不需要子查询。 对日期使用标准格式可以简化代码并使其更具可读性。 表别名使代码更易于编写和阅读。M_Gn_Desk
未使用,因此应从查询中删除。
【讨论】:
以上是关于Sql PIVOT,如何使用 PIVOT 将结果中的 NULL 转换为值 0的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 2008 中的 PIVOT / UNPIVOT