Monday 15 April 2013

sql - Append a column values from multiple rows into a string -


Does this valid SQL add values ​​of a column to a number of records in a string result? Announcement @ Results NVARCHAR (MAX) SET @ Result = '' SELECT @ Result = @ Result + Answer + ';' Answer: Where to answer A.Quiz_ID = 1 and A.Question_Id = 1 ORDER Answer @ Result [List of Answers]

The result should look like this:

  You can repeat the question; No; Yes;   

This is just an example. My question is this valid SQL? The reason I ask is that this technique breaks into my real code and breaks with an order by clause. In my "real" code I get the value from only one row.

To achieve your goal, STUFF () and Group BY

  SELECT q.Question + ';; Answer: Answer from where: Question_ID = xml path ('') for type 1 by q.Question_Id, type). Value ('.', 'NVARCHAR (MAX)'), 1,1, Answer: Answer a question on q.Question_Id = a.Question_Id group by q.Question_Id, q.Question   

sample output:

 | Results | ----------------------------------------------- | Can you repeat the question; Maybe; No; Yes. | Can you really repeat the question; Sure, yes.  

This is demo

if the answers are answered without any questions and you want to show them properly, then you ISNULL () < / Code> or COALESCE () (inject a default value for example)

  SELECT q.Question + ';' Order for xml path ('', type) for 1 by ISNULL (STUFF ((SELECT ';' Answer: Question_ID = q.Question_Id), value ('.', 'NVARCHAR (MAX)'), 1 , 1, ''), '[sorry, no answer now]' result from question q Answer: Answer a q.Question_Id = a.Question_Id by the group q.Question_Id, q.Question   

sample output:

 | results | -------------------------------- ------------------ -------- | Can you repeat the question; perhaps; no; yes | | can you really repeat the question; Sure, yes! | One quarter There is no answer; [Sorry, no answer yet] |  

The is demo

No comments:

Post a Comment