SQL Server PIVOT - 垂直到水平 - 错误

时间:2015-07-31 06:32:30

标签: pivot

请帮忙检查一下吗?

CREATE TABLE Sales 
(
    Category NVARCHAR(30),
    Region NVARCHAR(30),
    Amount MONEY
)

DELETE FROM Sales

INSERT INTO Sales
VALUES 
('X','1',24),
('X','2',NULL),
('X','3',165),
('X','4',36),
('Y','1',38),
('Y','2',181),
('Y','3',287),
('Y','4',NULL),
('Z','1',83),
('Z','2',55),
('Z','3',33),
('Z','4',44)

DECLARE @SQLStr NVARCHAR(MAX)

SELECT @SQLStr = COALESCE(@SQLStr + ',' ,'')+ [a].[Column]
FROM (SELECT DISTINCT Region AS [Column]
      FROM Sales) AS a

SET @SQLStr = 'SELECT Category, ' + @SQLStr + ' FROM (SELECT Category, Region, Amount FROM Sales) sq '
              + ' PIVOT (SUM(Amount) FOR Region IN (' + @SQLStr + ')) AS pt'
PRINT @SQLStr
EXEC sp_executesql @SQLStr

我收到错误

  

Msg 102,Level 15,State 1,Line 35
  “1”附近的语法不正确。

最初,“Region”列是INT类型(值为1,2,3,4) 同样的错误,然后我将其类型更改为NVARCHAR(30),但同样的错误发生。请帮忙。

实际上,我想将垂直产品使用数据转换为水平。

请参阅图片链接

Please see this screen shot, this is what I really want to achieve

如您所见,日期转换为水平。我想将使用数据填充到水平方式以供我分析。请帮忙

列标题可以是日期吗?或者必须是字符串?

1 个答案:

答案 0 :(得分:0)

请添加包含列名的括号,如下所示

DECLARE @SQLStr NVARCHAR(MAX)
SELECT @SQLStr = COALESCE(@SQLStr + ',' ,'')+ +'['+[a].[Column]+']'
FROM (SELECT DISTINCT Region AS [Column]
FROM @Sales) AS a

您应该始终在列名[]:

周围放置方括号

来自MSDN:

第一个字符必须是以下之一:

A letter as defined by the Unicode Standard 3.2. The Unicode definition of letters includes Latin characters from a through z, from A through Z, and also letter characters from other languages.
The underscore (_), at sign (@), or number sign (#).

如果是其他任何内容,则需要使用方括号。 []