使用

时间:2017-10-26 23:54:03

标签: mysql sql group-by

我有一个包含ff字段的quiz_tracking表(在mysql中):

subjectid - the id of the subject ( think of your subjects in school)
assessmentname - the name of the assessment ( think of it as exam or like chapter exams, the exams you found at the end of each chapter) found in each subject
questionid - the id of the question
userid - the id of the user who took the exam
attempt - attempt number
answer - answer given
score - score gained for this question

rownum - disregard this column, i only put in this one so its easier to point out which row numbers i am particularly interested in. 

当用户进行测验时,记录将记录在此处。评估的问题数量不同。对于这个例子,第一次评估有3次,第二次评估有3次,第三次评估有1.用户可以将测验留在中间,在这种情况下,答案栏将为空,因为测验者放弃了它。

我为表和数据创建了一个sql小提琴。

http://sqlfiddle.com/#!9/a41473/1

基本上,我想要提出的是我需要过滤此数据集并提供仅包含已完成的评估尝试的数据集。这意味着,如果评估有3个问题并且所有这些问题都得到了回答(答案不为空)那么那应该在过滤后的数据集中。

我想出如何确定是否有完整的评估的方式是通过这个sql:

select max(a.question_count) from ( 
select count(distinct qt.questionid) as 'question_count'
      from quiz_tracking qt
      where qt.subjectid=22380
      and qt.assessmentname = 'first assessment'
      and qt.userid in (555,121)
      group by qt.attempt, qt.userid ) a )

我计算所有问题ID。然后我做了

having ( sum(if(answer is not null,1,0)) = result of above subquery.

这里的假设是,     提供了主体,     提供所有评估名称     提供了所有用户标识。

在sql小提琴中,我可以进行1次评估(例如'第一次评估'),但我需要做的是生成包含所有评估的过滤数据集(第一次评估,第二次评估,第三次评估)。预期结果应为行号1,2,3,4,5,6,12,13,14,15,16,17,21,22。

1 个答案:

答案 0 :(得分:1)

只需将主表连接到计算问题计数和答案计数的聚合派生表,然后在外部查询返回时两者都相等:

select z.*, q_cnt.question_count, q_cnt.answer_count
from  quiz_tracking z

inner join
  (select c.userid, c.subjectid, c.assessmentname, c.attempt,
          count(distinct c.questionid) as 'question_count',
          sum(if(c.answer is not null,1,0)) as 'answer_count'
   from quiz_tracking c
   group by c.userid, c.subjectid, c.assessmentname, c.attempt) q_cnt

on q_cnt.userid = z.userid
and q_cnt.subjectid = z.subjectid
and q_cnt.assessmentname = z.assessmentname
and q_cnt.attempt = z.attempt

where  q_cnt.question_count = q_cnt.answer_count

SQL Fiddle DEMO