我有三张桌子,我已经删除了对我的问题不必要的信息,所以这就是为什么它们看起来光秃秃,毫无意义。
会话
SessionId (int) PK
答案
AnswerId (int) PK
AnswerDetail (varchar)
QuestionNumber (int)
IsCorrect (bit, null)
SessionAnswers
SessionAnswerId (int) PK
QuestionNumber (int)
SessionId (int) FK
AnswerId (int) FK
想象一下有10个问题,我希望每个Session
都有一行,然后每个问题和答案都在同一行。即对于每个Session
,它应该向我显示每个问题编号和该会话的答案。
不幸的是,我没有直接编写SQL几年,所以我有点困难让它重新开始。到目前为止,我已设法显示此数据,但它为会话提供的每个答案提供了一个新行。
SELECT dbo.Sessions.SessionId, dbo.Answers.IsCorrect, dbo.Answers.QuestionNumber
FROM dbo.Answers INNER JOIN
dbo.SessionAnswers ON dbo.Answers.AnswerId = dbo.SessionAnswers.Answer_AnswerId INNER JOIN
dbo.Sessions ON dbo.SessionAnswers.Session_SessionId = dbo.Sessions.SessionId
我应该考虑什么来满足我的目标?我不确定如何遍历每个SessionAnswer
这是我目前看到的::
但我想看到的是:
SessionId | Date | QuestionNumber1 | IsCorrect | QuestionNumber2 | IsCorrect
------------------------------------------------------------------------------
1 | Date | AnswerDetail1 | IsCorrect1 | AnswerDetail2 | IsCorrect2
即。我图片中的1-12行应该在同一行
答案 0 :(得分:1)
SELECT S.SessionId
, A1.AnswerDetail AS AnswerDetail1
, A1.IsCorrect AS IsCorrect1
, A2.AnswerDetail AS AnswerDetail2
, A2.IsCorrect AS IsCorrect2
, A3.AnswerDetail AS AnswerDetail2
, A3.IsCorrect AS IsCorrect2
-- ...
FROM Sessions AS S
-- Question 1
INNER JOIN SessionAnswers AS SA1
ON SA1.SessionId = S.SessionId
AND SA1.QuestionNumber = 1
INNER JOIN Answers AS A1
ON A.AnswerId = SA1.AnswerId
-- Question 2
INNER JOIN SessionAnswers AS SA2
ON SA2.SessionId = S.SessionId
AND SA2.QuestionNumber = 2
INNER JOIN Answers AS A2
ON A.AnswerId = SA2.AnswerId
-- Question 3
INNER JOIN SessionAnswers AS SA3
ON SA3.SessionId = S.SessionId
AND SA3.QuestionNumber = 3
INNER JOIN Answers AS A3
ON A.AnswerId = SA3.AnswerId
-- ...
我根据您的更新重写了这个答案。要查看以前的版本,请查看帖子历史记录。
答案 1 :(得分:1)
您想对所选行做什么?
您可以选择分层数据FOR XML
并获取一个非常容易进一步解析的XML文档。
例如
SELECT dbo.Sessions.SessionId, dbo.Answers.IsCorrect, dbo.Answers.QuestionNumber
FROM dbo.Answers
INNER JOIN dbo.SessionAnswers ON dbo.Answers.AnswerId = dbo.SessionAnswers.Answer_AnswerId
INNER JOIN dbo.Sessions ON dbo.SessionAnswers.Session_SessionId = dbo.Sessions.SessionId
FOR XML AUTO