【问题标题】:create view from multiple row into one row从多行创建视图到一行
【发布时间】:2014-05-07 17:35:55
【问题描述】:

我有两张桌子;一问一答

问题表

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

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

【问题讨论】:

  • 您使用的是哪个 RDBMS?
  • mssql 2008 @HamletHakobyan

标签: sql vb.net view


【解决方案1】:

您可以使用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

【讨论】:

  • 问题出在哪里?如果您对每个问题有 3 个答案,它将起作用。
  • 如果我不想随机怎么办?
  • @Sheldon 你是什么意思?
【解决方案2】:

下一个查询

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

将返回带有额外列的答案表,以表示答案所在的列。 “order by 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, ...

然后你加入一个问题来添加问题文本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2011-09-10
    • 2012-04-15
    • 2014-09-04
    相关资源
    最近更新 更多