如何使用动态SQL替换数据透视表中的空值

时间:2013-01-31 13:38:21

标签: sql null pivot

  

可能重复:
  How to Replace Nulls in PIVOT in SQL

我正在使用以下动态SQL:

 select *
    from #tempfinaltable
    pivot (sum(TotalXSAAL) for Section_desc in
    ' + '('+@BranchNames++')) AS AALs'

这与上述查询相同

select *
from #tempfinaltable
pivot (sum(TotalXSAAL) for Section_desc in
([Communication],[Construction],[Energy],[Financial Institutions],
 [General Property],[HIGHER ED & HEALTHCARE],
 [Inland Marine],[Real Estate])) AS AALs

我想要做的是在运行此查询时将空值替换为零。

我尝试使用ISNULL,以便我可以将其替换为零,但它不起作用。在IsNull附近说错误的syantax。任何想法如何解决它?

select *
from #tempfinaltable
pivot IsNull((sum(TotalXSAAL),0) for Section_desc in
([Communication],[Construction],[Energy],[Financial Institutions],
 [General Property],[HIGHER ED & HEALTHCARE],
 [Inland Marine],[Real Estate])) AS AALs

我也试过这样做,但它也没有用。

select Section_Desc, Zone, ISNULL(Sum(TotalXSAAL),0)
from #tempfinaltable
pivot (sum(TotalXSAAL) for Section_desc in
([Communication],[Construction],[Energy],
 [Financial Institutions],[General Property],
 [HIGHER ED & HEALTHCARE],[Inland Marine],
 [Real Estate])) AS AALs

另外,我的数据中没有任何空值,但是当我使用数据透视表时,结果显示为null。不知道为什么。

Example Data
Section_Desc    Zone    TotalXSAAL
Energy           Zone1  0
Energy           Zone2  0
Energy           Zone10 452
Energy           Zone2  1123
Energy            Zone3 87

Sameple Ouput:
ZONE    Communication   Construction    Energy  Financial Institutions  General  property   Higher Ed & Healthcare  Inland Marine   Real estate
ZONE1   10221   NULL    42124   89214211    911243  NULL    123120  1234235

答案就在这里: How to Replace Nulls in PIVOT in SQL

1 个答案:

答案 0 :(得分:0)

在旋转之前准备临时表中的数据。

ISNULL(FieldName, '0') as FieldName