﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / SQL Server 2008 / SQL Server 2008 - General  / Help needed with a query (Cursors+union+pivot?) / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Sat, 25 May 2013 03:15:02 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>Thank you everybody!ChrisM@Work's solution works for me.I only needed to increase the varchar size to 8000 to accommodate more Questions.Not sure if there is a neater solution, but this one works well for now.Thanks ChrisM@Work and thank you all!</description><pubDate>Tue, 02 Oct 2012 09:01:48 GMT</pubDate><dc:creator>gianlud75</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>Need to modify it slightly to fit your requirements. but this is my solution to rotate table verticallyLook like forum does not allow the drop statements for temporary tables, that was why it blew up (both on IE and firefox), so add  3 drop statements for temp tables at the end.[code="sql"]--create some test tables with test data for demo purposecreate table #question (questionId int identity(1,1), question varchar(100) )create table #answer (answerId int identity(1,1), questionId int,  answer  varchar(100))insert into #question(question)select 'You are old?' union allselect 'You are smart?' union allselect 'You are rich?' union all select 'You are loved?'insert into #answer(questionId, answer)select 1,'True' union allselect 2,'False' union allselect 3,'False'   --retrieve desired datacreate table #temp (fieldName  varchar(100),fieldValue  varchar(100), sortOrder int identity(1,1) )insert into #temp(fieldName,fieldValue)exec ('select question, answer from #answer right join #question on #answer.questionid=#question.questionId where 1=1');--generate sql statement to rotate table dynamically  declare @sql as varchar(8000)set @sql = 'select '; select @sql = @sql + '[' + fieldName+']=isnull((select fieldValue from #temp where fieldName='''+fieldName+'''),null),' from #temporder by sortOrder set @sql = SUBSTRING(@sql, 1, LEN(@sql)-1)print @sqlexec(@sql) [/code]</description><pubDate>Tue, 02 Oct 2012 07:25:17 GMT</pubDate><dc:creator>haiao2000</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>[quote][b]gianlud75 (10/2/2012)[/b][hr]...What I would like to get, is something like the image in attachment[/quote]You have to use dynamic sql for this. The core query is this:[code="sql"]SELECT 	a.SURV_ID, 	[First Question] = MAX(CASE WHEN q.QUES = 'First Question' THEN a.ANSW ELSE NULL END),	[Second Question] = MAX(CASE WHEN q.QUES = 'Second Question' THEN a.ANSW ELSE NULL END)	 FROM [QUESTIONS] qLEFT JOIN [ANSWERS] a 	ON a.QUES_ID = q.IDGROUP BY a.SURV_ID[/code]However, the questions cannot be hard-coded, they have to come from the data. So, we build up the statement using the data from the questions table:[code="sql"]DECLARE @Statement VARCHAR(1000)SET @Statement = 'SELECT a.SURV_ID'SELECT 	@Statement = @Statement + ','+CHAR(10)+'   [' + q.QUES + '] = MAX(CASE WHEN q.QUES = ''' + q.QUES + ''' THEN a.ANSW ELSE NULL END)'FROM [QUESTIONS] qORDER BY q.IDSET @Statement = @Statement + '	FROM [QUESTIONS] q	LEFT JOIN [ANSWERS] a 		ON a.QUES_ID = q.ID	GROUP BY a.SURV_ID' 	PRINT @StatementEXEC (@Statement)[/code]Heres the result of the PRINTSELECT a.SURV_ID,   [First Question] = MAX(CASE WHEN q.QUES = 'First Question' THEN a.ANSW ELSE NULL END),   [Second Question] = MAX(CASE WHEN q.QUES = 'Second Question' THEN a.ANSW ELSE NULL END)FROM [QUESTIONS] qLEFT JOIN [ANSWERS] a 	ON a.QUES_ID = q.IDGROUP BY a.SURV_ID;-)EDIT: added result of PRINT</description><pubDate>Tue, 02 Oct 2012 04:00:14 GMT</pubDate><dc:creator>ChrisM@Work</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>Hi,this does the job[code="sql"]SELECT DISTINCT a.Surv_id, (SELECT ANSW FROM ANSWERS t WHERE t.QUES_ID = 1 AND t.SURV_ID = a.SURV_ID) [First Question], (SELECT ANSW FROM ANSWERS t WHERE t.QUES_ID = 2 AND t.SURV_ID = a.SURV_ID) [Second Question] FROM ANSWERS a[/code]But the questions are "hard coded"... [code="sql"] t.ID = 1 .. [/code]With PIVOT the result is the same but, like all PIVOT, the columns (referring the questions) are also "hard coded"[code="Sql"]SELECT SURV_ID, [First Question], [Second Question]FROM (	SELECT s.SURV_ID, q.QUES, a.ANSW FROM 	(		(SELECT DISTINCT SURV_ID FROM ANSWERS) s		CROSS JOIN Questions q 		LEFT JOIN ANSWERS a ON a.SURV_ID = s.SURV_ID AND q.ID = a.QUES_ID	) )AS SrcData	PIVOT (	MAX(ANSW) 	FOR QUES IN ([First Question], [Second Question])	) AS pivotData[/code]You can build a dynamic SQL and execute it to build the query according to the existing questions.Pedro</description><pubDate>Tue, 02 Oct 2012 03:21:47 GMT</pubDate><dc:creator>PiMané</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>Hi Lowell,thank you for you help so far. The problem that I am facing is a bit more complicated, since not the questions have an answer (in that case I'm happy to show NULL), and answers are grouped by a SURV_ID[code="sql"]CREATE TABLE [QUESTIONS] (	[ID] [int] IDENTITY(1,1) NOT NULL,	[QUES] [varchar](250) NOT NULL,	[ORD] [int] NOT NULL, CONSTRAINT [PK_QUESTIONS] PRIMARY KEY CLUSTERED (	[ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOINSERT INTO [QUESTIONS] values ('First Question', 1)INSERT INTO [QUESTIONS] values ('Second Question', 2)GOCREATE TABLE [ANSWERS] (	[ID] [int] IDENTITY(1,1) NOT NULL,	[SURV_ID] [int] NOT NULL,	[QUES_ID] [int] NOT NULL,	[ANSW] [varchar](500) NOT NULL, CONSTRAINT [PK_ANSWERS] PRIMARY KEY CLUSTERED (	[ID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY]GOSET ANSI_PADDING OFFGOALTER TABLE [ANSWERS]  WITH CHECK ADD  CONSTRAINT [FK_ANSWERS_QUESTIONS] FOREIGN KEY([QUES_ID])REFERENCES [QUESTIONS] ([ID])GOALTER TABLE [ANSWERS]   CHECK CONSTRAINT [FK_ANSWERS_QUESTIONS]GOINSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (1,1,'Y')INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (1,2,'N')INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (2,1,'N')INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (3,2,'Y')INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (4,1,'Y')INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (4,2,'Y')GO[/code]What I would like to get, is something like the image in attachment</description><pubDate>Tue, 02 Oct 2012 02:35:38 GMT</pubDate><dc:creator>gianlud75</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>[quote][b]haiao2000 (10/1/2012)[/b]you bet!!!, that is the first thing I tried. it didnt work. some days it just doesn't work. everytime I hit submit it just blows up like overloaded balloon.[code="sql"] it said: Internet Explorer could find the webpage....shame!  [/code][/quote]I use FireFox :-) No problem with that...</description><pubDate>Mon, 01 Oct 2012 15:54:10 GMT</pubDate><dc:creator>PiMané</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>[quote][b]PiMané (10/1/2012)[/b][hr][quote][b]haiao2000 (10/1/2012)[/b][hr]For some reasons, everyone a while I COULD NOT post the code using any of IFcode. there is some issue with @ or #. Anyone see similar issue witht this forum?I was about to post my solution. but I couldn't...frustrated.[/quote]Put the code in [code="sql"][code="sql"]...\[/code][/code][/quote]you bet!!!, that is the first thing I tried. it didnt work. some days it just doesn't work. everytime I hit submit it just blows up like overloaded balloon.[code="sql"] it said: Internet Explorer could find the webpage....shame!  [/code]</description><pubDate>Mon, 01 Oct 2012 15:44:27 GMT</pubDate><dc:creator>haiao2000</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>[quote][b]haiao2000 (10/1/2012)[/b][hr]For some reasons, everyone a while I COULD NOT post the code using any of IFcode. there is some issue with @ or #. Anyone see similar issue witht this forum?I was about to post my solution. but I couldn't...frustrated.[/quote]Put the code in  [ code="sql" ]...[ /code ] (had to put spaces before and after the [ and ] so the code would be processed...)[code="sql"]@ # no problem...[/code]</description><pubDate>Mon, 01 Oct 2012 15:39:29 GMT</pubDate><dc:creator>PiMané</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>For some reasons, everyone a while I COULD NOT post the code using any of IFcode. there is some issue with @ or #. Anyone see similar issue witht this forum?I was about to post my solution. but I couldn't...frustrated.</description><pubDate>Mon, 01 Oct 2012 13:16:06 GMT</pubDate><dc:creator>haiao2000</dc:creator></item><item><title>RE: Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>there's no need for a cursor on this, but I think youa re right, you will need to pivot the rows to columns;is there a fixed number of answers for each question, or does it vary?is there a maximum number of answers for each question, ie 4 for a multipel choice question?here's an example i adapted, since i didn't want to guess at your DDL for your tables.note that if you can provide the data in the same format int he future, you can get exact, tested answers to your problems:[code]CREATE TABLE Question (QuestionID INT , QuestionName VARCHAR(255))INSERT INTO Question values (1,'First Question')INSERT INTO Question values (2,'Second Question')goCREATE TABLE Question_items (QuestionID INT , ItemID INT )INSERT INTO Question_items values (1, 10)INSERT INTO Question_items values (1, 20)INSERT INTO Question_items values (1, 30)INSERT INTO Question_items values (1, 40)INSERT INTO Question_items values (2, 50)INSERT INTO Question_items values (2, 60)INSERT INTO Question_items values (2, 70)INSERT INTO Question_items values (2, 80)go;with cte as (        select QuestionID ,ItemID,         row_number() over (partition by QuestionID order by ItemID desc) RN        from Question_items) --select * from select QuestionID,[1] as Val1,[2] as Val2,[3] as Val3,[4] as Val4 from         ( select * from cte where RN &amp;lt;= 4 ) pivot_handlepivot    (MAX(ItemID) for RN in ([1],[2],[3],[4])) pivot_table[/code]</description><pubDate>Mon, 01 Oct 2012 09:58:46 GMT</pubDate><dc:creator>Lowell</dc:creator></item><item><title>Help needed with a query (Cursors+union+pivot?)</title><link>http://www.sqlservercentral.com/Forums/Topic1366628-391-1.aspx</link><description>Hello,I've been trying to figure out how to solve this for a while, with no success.I have 2 tables:1)QUESTIONS  ID (pk)  QUES  ORD2)ANSWERS   ID (pk)   QUES_ID (fk)   SURV_ID (fk)   ANSWNow I need to create a view, where the questions are the columns names and for each SURV_ID there is a row in the view with answer NULL if there is no entry in ANSWERS or answer ANSW if there is an entry.Not sure if it is possible to do it with JOINs.I was thinking to use a CURSOR, then do the UNION of the resulting tables, then use a PIVOT, but not sure it's the best solutions + I don't know how to do the union through the loops...DECLARE @survID intDECLARE db_cursor CURSOR FOR  SELECT DISTINCT SURV_ID FROM ANSWERS ORDER BY SURV_IDOPEN db_cursor  FETCH NEXT FROM db_cursor INTO @survID  WHILE @@FETCH_STATUS = 0  BEGIN	SELECT QUES		  ,ANSW , SURV_ID	  FROM QUESTIONS a	 left  outer JOIN ANSWERS b ON a.ID = b.QUES_ID 	  WHERE ( SURV_ID = @survID  OR SURV_ID IS NULL)FETCH NEXT FROM db_cursor INTO @survID END  CLOSE db_cursor  DEALLOCATE db_cursor ....Thanks for your time and your help!</description><pubDate>Mon, 01 Oct 2012 09:36:21 GMT</pubDate><dc:creator>gianlud75</dc:creator></item></channel></rss>