Create table #temp
(Member_ID Varchar(30),question_text Varchar(100),response int)
Insert into #temp
Select '0562773*01','In general would you say your health is?',2 union all
Select '0562773*01','How would you rate your health today?',1 union all
Select '0562773*01','How would you rate your emotional health now?',1 union all
Select '9962773*01','In general would you say your health is?',5 union all
Select '9962773*01','How would you rate your health today?',1 union all
Select '9962773*01','How would you rate your emotional health now?',3
--PIVOT Query
Declare @SQL NVarchar(Max)
DECLARE @FieldList VARCHAR(MAX)
SELECT @FieldList =
STUFF(( SELECT distinct '],[' + question_text FROM #temp
FOR XML PATH('')
), 1, 2, '') + ']'
Set @SQL =
'SELECT Member_ID,' + @FieldList + '
FROM
(
SELECT Member_ID,question_text,response
FROM #temp
)P
PIVOT (MAX(response) for question_text in ( ' + @FieldList + '))as pvt'
EXEC (@SQL)
Member_ID How would you rate your emotional health now? How would you rate your health today? In general would you say your health is?
0562773*01 1 1 2
9962773*01 3 1 5