将视图从多行创建为一行

时间:2014-05-07 17:35:55

标签: sql vb.net view

我有两张桌子;问答

问题表

QuestionID QuestionText
1          Question1
2          Question2
3          Question3
答案表。它有fk问题表和位来确定答案是否正确

answerID answer_question_id(fk) answertxt answer_isright
1          1                    answer1   1
2          1                    answer2   0
3          1                    answer3   0
4          2                    answer1   1
5          2                    answer2   0
6          2                    answer3   0

那么如何创建第一列是问题的视图,第二列,第三列和第四列是答案(随机)?

2 个答案:

答案 0 :(得分:0)

下一个查询

SELECT answerid, answer_question_id, answer_isright, 
row_number() over (partition by answer_question_id order by newid()) as rnum
from answers

将返回带有额外列的答案表,以表示答案所针对的列。 "按newid()"排序不是标准的一部分,对每个数据库供应商都不同。

answerId  .... rnum
1              1    
2              3
3              2    
4              3
5              1    
6              2

(每次执行时rnums都不同)

然后您使用此查询根据rnum

将答案移动到不同的列
select answerid, ..., case when rnum = 1 then answertxt else null end co1, ...

这将移动你的文字:

answerId  .... rnum ... col1,   col2   col3
1              1        text1   null   null
2              3        null    null   text2
3              2        null    text3  null
4              3        null    null   text4
5              1        text5   null   null
6              2        null    text6  null

然后你需要对它们进行分组:

select answer_question_id, .., max(col1), max(col2), max(col3) from prev_query
group by answer_question_id, ...

然后您加入问题以添加问题文本

答案 1 :(得分:0)

您可以使用PIVOT解决问题:

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