使用视图的非随机回答

时间:2014-06-01 08:03:13

标签: asp.net sql sql-server vb.net view

我创建了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进行演示

1 个答案:

答案 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

即可