从一个列中加入多个值,从另一个表中选择

时间:2015-03-03 09:40:19

标签: sql sql-server tsql csv join

鉴于这些简化的多选表,有时候不止一个答案是正确的:

STUDENT_ANSWERS
AnswerID | StudentID | QuestionID | Answers
-------------------------------------------
       1 |         1 |          1 | C,D

QUESTION_ANSWERS
QuestionID | Answer | Text
-------------------------------------------------
         1 |      A | This is answer A
         1 |      B | B could also be correct
         1 |      C | Maybe it's C?
         1 |      D | Definitely D!

如何进行选择,将答案翻译成其描述?

我的开始:

SELECT *
FROM STUDENT_ANSWERS sa
LEFT OUTER JOIN QUESTION_ANSWERS qa ON qa.Answer IN sa.Answers???
 -- Doesn't seem to work as IN requires a format of ('C','D') while I have 'C,D'

期望的输出:

AnswerID | StudentID | QuestionID | AnswerDescriptions
-------------------------------------------
       1 |         1 |          1 | Maybe it's C?,Definitely D!

因此,描述只需替换代码而不是每个答案都有一行。

3 个答案:

答案 0 :(得分:2)

您的问题是表格STUDENT_ANSWERS的结构。每个答案应该有一行:

AnswerID | StudentID | QuestionID | Answer
-------------------------------------------
       1 |         1 |          1 | C
       2 |         1 |          1 | D

现在,假设你无法做任何改变(阅读:修复)这个,你可以通过附加逗号和使用LIKE来捏造它:

select *
from STUDENT_ANSWERS a
join QUESTION_ANSWERS q on ',' + a.Answers + ',' like '%,' + q.Answer + ',%'
    and a.QuestionID = q.QuestionID

SQL Fiddle demo

请注意,假设您永远不会在, 中找到文字QUESTION_ANSWERS.Answer。它也永远不能使用索引,所以它会比慢速慢。

如果绝对必须将数据库中的格式设置为一行,您可以使用STUFFFOR XML PATH('')技巧来连接生成的行。

答案 1 :(得分:1)

这是仅使用T-SQL语句的完整工作示例。我将建议您创建单独的函数来拆分返回行集的CSV。此外,如果您正在处理大量数据,则可能需要创建CLR函数来分割值。看看this article(你需要的一切)。

DECLARE @StudentAnswers TABLE
(
     [AnswerID] INT
    ,[StudentID] INT
    ,[QuestionID] INT
    ,[Answers] VARCHAR(256)
);

DECLARE @QuestionAnswers TABLE
(
     [QuestionID] INT
    ,[Answer] CHAR
    ,[Text] VARCHAR(256)
);

INSERT INTO @StudentAnswers ([AnswerID], [StudentID], [QuestionID], [Answers])
VALUES (1, 1, 1, 'C,D')
      ,(2, 2, 1, 'A');

 INSERT INTO @QuestionAnswers ([QuestionID], [Answer], [Text])
 VALUES  (1, 'A', 'This is answer A')
        ,(1, 'B', 'B could also be correct')
        ,(1, 'C', 'Maybe it''s C?')
        ,(1, 'D', 'Definitely D!');

SELECT SA.[AnswerID]
      ,SA.[StudentID]
      ,SA.[QuestionID]
      ,T.c.value('.', 'CHAR')
      ,QA.[Text]
FROM @StudentAnswers SA
CROSS APPLY 
(
    SELECT CAST('<i>' + REPLACE([Answers], ',', '</i><i>') + '</i>' AS XML) Answers
) DS
CROSS APPLY DS.Answers.nodes('i') T(c)
INNER JOIN @QuestionAnswers QA
    ON SA.[QuestionID] = QA.[QuestionID]
    AND T.c.value('.', 'CHAR') = QA.[Answer];

答案 2 :(得分:0)

试试这个

select answerid,studentid,a.QuestionID,group_concat(b.text) from student_answers a left join QUESTION_ANSWERS b on b.questionid= a.questionid and  FIND_IN_SET(b.Answer, a.Answers)
group by a.questionid

绝对有效。