如何在数据透视SQL查询中将null替换为零

时间:2018-07-09 09:10:28

标签: sql-server

我正在尝试获取

的按年和按月销售
 select * from
 (
 select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month], 
 InvAmnt as Amount
 from tblInvoice where TenantId =-xxxxxxxx
 ) as Inv
 pivot
 (sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, 
  Oct, Nov, [Dec])) as pvt

enter image description here 但是这里有很多null,所以我想将这些null替换为零。 请帮助我。

3 个答案:

答案 0 :(得分:2)

test01.php

答案 1 :(得分:1)

所以答案是这样,但是它太长了,我们必须要有另一种解决方案,但是我现在还不能解决

select [Year], isnull(Jan, 0) as Jan,isnull(Feb,0) as Feb, isnull(Mar, 0) as 
Mar, isnull(Apr, 0) as Apr, isnull(May,0) as May, 
isnull(Jun,0) as Jun, isnull(Jul,0) as Jul, isnull(Aug,0) as Aug, 
isnull(Sep,0) as Sep,isnull(Oct,0) as Oct, isnull(Nov,0) as Nov, 
isnull([Dec],0) as Dec
from
(
select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month], 
InvAmnt as Amount
from tblInvoice where TenantId =-xxxxxxx
) as Inv
pivot
(sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, 
Oct, Nov, [Dec])) as pvt

感谢Mazhar的解决方案,我的思想得以打开并得以解决。

答案 2 :(得分:0)

只需在子查询中添加合并语句即可将零替换为空:

 select * from
     (
     select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month], 
     coalesce(InvAmnt, 0) as Amount
     from tblInvoice where TenantId =-xxxxxxxx
     ) as Inv
     pivot
     (sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, 
      Oct, Nov, [Dec])) as pvt)