我在表格问题和表格答案中有一个查看列。表格问题有id和问题文本,而表格答案有id,question_id(来自表格问题的fk)和答案文本。
SELECT
QuestionID, QuestionTxt, [1], [2], [3], [4]
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID
ORDER BY newid()) AnswerInQuestionID,
a.AnswerTxt, q.QuestionTxt, q.QuestionId
FROM
dbo.TblQuestion q
JOIN
dbo.TblAnswer a ON q.QuestionId = a.answer_question_id) A
PIVOT (MAX(a.AnswerTxt) FOR AnswerInQuestionID IN ([1], [2], [3], [4])) AS piv
从这个SQL中,我可以随机化答案,但它只显示文本。我想要文本答案和它的id
答案 0 :(得分:1)
很难从你的问题中找出你希望获得AnswerID的地方。如果您想将它放在一个列中,则需要使用@ StayPuft的答案。如果您希望它作为文本列的一部分,您可以使用下面的SQL:
SELECT questionText, [1], [2], [3]
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid()) AnswerInQuestionID,
CAST(AnswerID AS VARCHAR(20)) + ' - ' + answerTxt AS answerTxt,
QuestionText
FROM questions q
JOIN answers a
ON q.QuestionID=a.answer_question_id
) A
PIVOT
(
MAX(answerTxt)
FOR AnswerInQuestionID IN ([1], [2], [3] )
) as piv
如果您希望将它们作为三个单独的列,则可以使用以下SQL:
SELECT
questionText,
LEFT([1], 1) AS AnswerID1,
RIGHT([1], LEN([1]) - 1) AS AnswerText1,
LEFT([2], 1) AS AnswerID2,
RIGHT([1], LEN([1]) - 1) AS AnswerText1,
LEFT([3], 1) AS AnswerID3,
RIGHT([2], LEN([3]) - 1) AS AnswerText3
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid()) AnswerInQuestionID,
CAST(AnswerID AS VARCHAR(20)) + answerTxt AS answerTxt,
QuestionText
FROM questions q
JOIN answers a
ON q.QuestionID=a.answer_question_id
) A
PIVOT
(
MAX(answerTxt)
FOR AnswerInQuestionID IN ([1], [2], [3] )
) as piv
编辑:添加了CHARINDEX()函数和管道('|')以允许不同的数字长度。可能有更简洁的方法,但这对我有用:
SELECT
questionText,
LEFT([1], CHARINDEX('|', [1]) -1) AS AnswerID1,
RIGHT([1], LEN([1]) - CHARINDEX('|', [1])) AS AnswerText1,
LEFT([2], CHARINDEX('|', [2]) -1) AS AnswerID2,
RIGHT([2], LEN([2]) - CHARINDEX('|', [2])) AS AnswerText2,
LEFT([3], CHARINDEX('|', [3]) -1) AS AnswerID3,
RIGHT([3], LEN([3]) - CHARINDEX('|', [3])) AS AnswerText3
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid()) AnswerInQuestionID,
CAST(AnswerID AS VARCHAR(20)) +'|'+ answerTxt AS answerTxt,
QuestionText
FROM questions q
JOIN answers a
ON q.QuestionID=a.answer_question_id
) A
PIVOT
(
MAX(answerTxt)
FOR AnswerInQuestionID IN ([1], [2], [3] )
) as piv
答案 1 :(得分:0)
看起来a.AnswerTxt不在你的主要选择中,只有QuestionID和QuestionTxt。将a.AnswerTxt添加到第一行。
答案 2 :(得分:0)
首先让我说SQL Fiddle真棒!
如果你想显示答案ID - 这就是我所做的:
SELECT questionText, [1], [2], [3], answerID
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid()) AnswerInQuestionID,
answerTxt,
QuestionText,
answerID
FROM questions q
JOIN answers a
ON q.QuestionID=a.answer_question_id
) A
PIVOT
(
MAX(answerTxt)
FOR AnswerInQuestionID IN ([1], [2], [3] )
) as piv