0

我有以下代码,我试图用零替换使用枢轴时出现的 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

我正在使用的动态 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
4

2 回答 2

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 小提琴演示

更新

如何生成部分动态 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
于 2013-01-31T13:01:11.333 回答
-1

如果你想NULL用空字符串替换 PIVOT TABLE 然后

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

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

于 2014-09-17T16:39:15.447 回答