我创建了2个表,这些表是表格问题和答案。我还创建了加入两个表的视图。
create table questions(QuestionID int, QuestionText varchar (500));
insert questions
values
(1, 'Question1'),
(2, 'Question2'),
(3, 'Question3');
create table answers(answerID int, answer_question_id int, answertxt varchar(500),
answer_isright bit);
insert answers
values
(1, 1, 'answer1', 1),
(2, 1, 'answer2', 0),
(3, 1, 'answer3', 0),
(4, 2, 'answer1', 1),
(5, 2, 'answer2', 0),
(6, 2, 'answer3', 0);
视图:
SELECT questionText, [1], [2], [3]
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY newid())
AnswerInQuestionID,
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 fiddle demo进行演示
答案 0 :(得分:1)
SELECT questionText, [1], [2], [3]
FROM
(
SELECT
ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY answerID) AnswerInQuestionID,
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 fiddle 只需将newid()更改为answerID
即可