0

下面的查询为我提供了每个调查(问题)的所有已回答问题、用户的答案和正确答案。

我想对其进行修改,以添加每个特定调查的已回答问题总数、正确答案总数 (correctAnswer) 和正确答案百分比?

select sq.question,
       sc.choice,
       sq.CorrectAnswer,
       sa.score from Survey s
 INNER JOIN SurveyQuestions sq ON s.surveyId = sq.SurveyId 
 INNER JOIN SurveyChoices sc ON sq.questionId=sc.questionId
 INNER JOIN SurveyAnswers sa ON sc.choiceId = sa.choiceId
 INNER JOIN tblLogin tl ON sa.username = tl.username
 WHERE tl.username = 'JohnSmith' and sq.surveyId = 12
 ORDER BY sq.questionId

`

Survey table:
    [SurveyID] [int] IDENTITY(1,1) NOT NULL,
    [Title] [varchar](50) NULL,
    [Description] [varchar](max) NULL

SurveyQuestions table
    [QuestionID] [int] IDENTITY(1,1) NOT NULL,
    [SurveyID] [int] NULL,
    [Question] [varchar](255) NULL,
    [AnswerType] [char](1) NULL,
    [CorrectAnswer] [nvarchar](255) NULL,
    [QuestionOrder] [int] NULL
SurveyChoices table
    [ChoiceID] [int] IDENTITY(1,1) NOT NULL,
    [QuestionID] [int] NOT NULL,
    [Choice] [nvarchar](255) NOT NULL


SurveyAnswers table
    [AnswerID] [int] IDENTITY(1,1) NOT NULL,
    [QuestionID] [int] NOT NULL,
    [ChoiceID] [int] NULL,
    [ChoiceText] [varchar](max) NULL,
    [UserName] [varchar](50) NULL

提前谢谢了

4

2 回答 2

0

尝试这样的事情

 select 
   Count(sq.surveyId) as 'total # of answered questions per survey'
   sq.question,
   sc.choice,
   sq.CorrectAnswer,
   sa.score from Survey s
 INNER JOIN SurveyQuestions sq ON s.surveyId = sq.SurveyId 
 INNER JOIN SurveyChoices sc ON sq.questionId=sc.questionId
 INNER JOIN SurveyAnswers sa ON sc.choiceId = sa.choiceId
 INNER JOIN tblLogin tl ON sa.username = tl.username
 WHERE tl.username = 'JohnSmith' and sq.surveyId = 12
 Group sq.question,
   sc.choice,
   sq.CorrectAnswer,
   sa.score
 ORDER BY sq.questionId
于 2013-07-22T20:46:03.183 回答
0

假设我正确阅读了您的问题,您当前的查询会为每个问题返回一行,但您想在此查询中包含调查数据吗?因此,对于每个问题,您还拥有该问题调查的答案数量和正确答案?

如果这是正确的,那么您可以使用 OVER-PARTITION BY来执行此操作。

select sq.question,
       sc.choice,
       sq.CorrectAnswer,
       sa.score,
       COUNT(*) OVER (PARTITION BY sq.SurveyId) AS TotalAnswers,
       COUNT(CASE WHEN sq.CorrectAnswer = 'RIGHT ANSWER' THEN 1 ELSE NULL END) OVER (PARTITION BY sq.SurveyId) AS CorrectAnswers
 FROM Survey s
 INNER JOIN SurveyQuestions sq ON s.surveyId = sq.SurveyId 
 INNER JOIN SurveyChoices sc ON sq.questionId=sc.questionId
 INNER JOIN SurveyAnswers sa ON sc.choiceId = sa.choiceId
 INNER JOIN tblLogin tl ON sa.username = tl.username
 WHERE tl.username = 'JohnSmith' and sq.surveyId = 12
 ORDER BY sq.questionId

一些变化来自于你在答案正确时如何抓取的细节(我目前从你的表格布局中没有明显地看到)等等。

于 2013-07-22T20:49:28.247 回答