I have a table like this:
And I want to change table structure to this format:
I used this query :
Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Q]) Frommytable Order by 1 For XML Path('')),1,1,'')
Select @SQL = 'Select [user],' + @SQL + '
From mytablle
Pivot ( sum(Answer) For [Q] in (' + @SQL + ') ) p'
Exec(@SQL);
But it didn't work as we can't use sum function for [Answer] (it's string). What is your guide for this problem?


MAX? Which version of SQL Server are you on?MINorMAXfunction should do the trick.