如何在SQL中替换PIVOT中的空值

时间:2013-01-31 12:58:00

标签: sql null pivot

我有以下代码,我正在尝试替换使用零轴时出现的Null。我执行以下操作,但它说“ISNULL'附近的语法不正确。”我不确定我做错了什么?请提出任何建议

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

我正在使用的dyanmic SQL。上面的查询只显示名称,以便您可以看到我正在使用的内容

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

你能告诉我这句话有什么不对吗?我有语法问题:

BEGIN 

    Set @ISNullBranchNames = @ISNullBranchNames + 'ISNULL('+(@BranchNames+',0),' 
    Set @BranchNames = @BranchNames + '['+@BranchName+'],'

    FETCH NEXT FROM CUR1 INTO @BranchName

END

2 个答案:

答案 0 :(得分:3)

所有PIVOT子句必须在括号中。

结果查询必须如下所示:

SELECT 
      'TotalXSAAL' as Col,
      ISNULL([Communication], 0) AS [Communication],
      ISNULL([Construction], 0) AS [Construction],
      ...,
      ...,
      ... 
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

<强> SQL FIDDLE DEMO

<强>更新

如何生成动态SQL的部分。

DECLARE @ISNullBranchNames nvarchar(MAX) = N'' -- you mast add empty string first, otherwise you will get NULL inresult
DECLARE @BranchNames nvarchar(MAX) = N''
.....
BEGIN 

    Set @ISNullBranchNames =
             @ISNullBranchNames + 'ISNULL([' + @BranchName + '], 0) AS [' + @BranchName +'], '
    Set @BranchNames = @BranchNames + '['+@BranchName+'],'

    FETCH NEXT FROM CUR1 INTO @BranchName

END

答案 1 :(得分:-1)

如果您想用空字符串替换PIVOT TABLE中的 NULL ,那么

ISNULL ( CAST (SUM(UnitPrice]) as NVARCHAR),'') 

这会将UnitPrice的SUM值转换为VARCHAR,然后使用ISNULL将其替换为空字符串