Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ezayas
Starting Member
1 Post |
Posted - 2012-12-19 : 18:17:03
|
I have been getting this error when executing the PIVOT query any help would be appreciated. Msg 102, Level 15, State 1, Line 19Incorrect syntax near '('.Data ##temp1 table columns are (Member_ID,question_text,response)Member_ID question_text response0562773*01 In general would you say your health is? 20562773*01 How would you rate your health today? 10562773*01 How would you rate your emotional health now? 19962773*01 In general would you say your health is? 59962773*01 How would you rate your health today? 19962773*01 How would you rate your emotional health now? 3--PIVOT Query DECLARE @FieldList VARCHAR(MAX) SELECT @FieldList = STUFF(( SELECT '],[' + question_text FROM ##temp1 FOR XML PATH('') ), 1, 2, '') + ']' SELECT Member_ID FROM ( SELECT t1.question_text , t1.response FROM ##temp1 AS t1 ) p PIVOT ( ([response]) FOR question_text IN ( @FieldList ) ) AS pvtORDER BY Member_ID; |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-12-19 : 19:34:19
|
Two things:1. You have to use an aggregate function for value to be pivoted.2. You cannot use a variable for the pivot list.....PIVOT ( MAX([response]) FOR question_text IN ( @FieldList ) ) AS pvt.... You may need to use dynamic pivoting to do what you are trying to do. See Madhivanan's blog. |
|
|
sodeep
Master Smack Fu Yak Hacker
7174 Posts |
Posted - 2012-12-19 : 21:57:27
|
[code]Create table #temp (Member_ID Varchar(30),question_text Varchar(100),response int)Insert into #tempSelect '0562773*01','In general would you say your health is?',2 union allSelect '0562773*01','How would you rate your health today?',1 union allSelect '0562773*01','How would you rate your emotional health now?',1 union allSelect '9962773*01','In general would you say your health is?',5 union allSelect '9962773*01','How would you rate your health today?',1 union allSelect '9962773*01','How would you rate your emotional health now?',3--PIVOT QueryDeclare @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,responseFROM #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 29962773*01 3 1 5[/code] |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
|
|
|
|
|
|