我使用此示例在问卷数据库上执行动态数据透视 Tricky SQL Server Pivot Table for Survey
唯一的补充是我有另一个名为AnswerWeight的整数列。我想总结所有答案权重,但我的SQL技能缺乏一点。
这是我目前的代码:
declare @SurveyID int = 1
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('QID:'+cast(questionid as varchar(10))+ ' - ' + Question)
from dbo.v_AnswersCombined where SurveyID = @SurveyID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ResponseID as ID, ' + @cols + ' from
(
select ResponseID, SurveyID,
(''QID:''+cast(questionid as varchar(10))+ '' - '' + [Question]) as question,
value
from
(
SELECT [ID]
,[SurveyName]
,[ResponseID]
,[QuestionID]
,[QuestionGroupID]
,[SurveyID]
,[QuestionTypeID]
,[Answer]
,[Question]
,[QuestionWeight]
,[QuestionOrder]
,[QuestionGroup]
,[QuestionGroupOrder]
,[AnswerWeight]
,[DateCreated]
FROM [dbo].[v_AnswersCombined] where surveyID=' + Cast(@SurveyID as nvarchar(20)) + '
) s
unpivot
(
value
for col in (Answer)
) un
) x
pivot
(
max(value)
for question in (' + @cols + ')
) p '
execute(@query)
任何帮助将不胜感激