我正在尝试创建一个数据透视表,其中列出了时间范围(responseText
)作为列,并根据提出的问题在该特定列下显示每个字符的平均答案。我试图用PIVOT
函数来做这件事 - 无济于事。
我有下表
我首先创建一个临时表并使用存储过程中的值填充它,然后我构建一个动态查询
CREATE TABLE #Data
(
QuestionText varchar(400),
ResponseText varchar(200),
AverageAnswer float
)
INSERT INTO #Data
EXECUTE AverageDemographicGroupAnswer @GroupID, @Survey, @Demographic
--SELECT * FROM #Data
DECLARE @PivotQuery NVARCHAR(MAX)
DECLARE @Cols varchar(max)
SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME(ResponseText,'[]') FROM dbo.SurveyResponses WHERE QuestionID = @Demographic FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
--SELECT @Cols
SET @PivotQuery = 'SELECT QuestionText, '+ @Cols +' FROM
(
SELECT QuestionText, ResponseText, AverageAnswer FROM #Data
)x
PIVOT
( AverageAnswer FOR ResponseText in (' + @Cols + ')
)p'
--select @PivotQuery
EXECUTE(@PivotQuery)
DROP TABLE #Data
产生此查询
SELECT QuestionText, [At least 1 year but less than 3 years],[At least 3 years but less than 5 years],[Less than 1 year],[More than 5 years] FROM (SELECT QuestionText, AverageAnswer, ResponseText FROM #Data) AS SourceTable
PIVOT( AverageAnswer FOR ResponseText in ([At least 1 year but less than 3 years],[At least 3 years but less than 5 years],[Less than 1 year],[More than 5 years])) AS PivotTable
但它正在返回此错误
关键字“FOR”附近的语法不正确。
这是我第一次创建一个支点,我不确定是什么问题