简体   繁体   English

将多个内部联接的行合并为多列的一行

[英]Combine multiple inner joined rows into one row with multiple columns

I have a Questions table and an Answers table that has 4 to 8 answers connected to one question. 我有一个问题表和一个答案表,其中有4到8个答案连接到一个问题。 When I want to get a list of questions and their answers, I use the following code: 当我想获取问题及其答案的列表时,请使用以下代码:

select q.QuestionID, q.Question, a.Answer
from Question as q inner join Answer as a
on q.QuestionID=a.QuestionID;

This gives me one row for each answer with the question being repeated on each row. 这给我每个答案一行,每一行重复一个问题。 However, I want to only get one row per question with the answers in separate columns. 但是,我只希望每个问题在单独的列中包含一行答案。 If possible, I'd like to also limit this to only 4 answers. 如果可能的话,我也想将其限制为仅4个答案。 If there are more than 4, the rest should just be ignored. 如果大于4,则应忽略其余部分。 This is however not as important. 但是,这并不重要。

The four answer columns would be named "Correct", "Wrong1", "Wrong2" and "Wrong3". 四个答案列将分别命名为“正确”,“错误1”,“错误2”和“错误3”。 The first one in the table (with the lowest AnswerID) is the correct one. 表中的第一个(具有最低的AnswerID)是正确的。

Thank you for your help! 谢谢您的帮助!

select q.QuestionID, q.Question, 
   CASE <some field>
   WHEN <condition> THEN a.Answer
   END as Correct,
   CASE <some field2>
   WHEN <condition2> THEN a.Answer
   END as Wrong1
   ...
from Question as q inner join Answer as a
on q.QuestionID=a.QuestionID
group by q.QuestionID

You can group by question and define conditioned fields for the "Correct", "Wrong1", "Wrong2" and "Wrong3" columns 您可以按问题分组并为“正确”,“错误1”,“错误2”和“错误3”列定义条件字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM