mysql - 使用 group by 的 sql 查询

标签 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 fiddle。

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.

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

在 sql fiddle 中,我可以针对 1 次评估(例如“第一次评估”)执行此操作,但我需要做的是生成一个包含所有评估(第一次评估、第二次评估、第三次评估)的过滤数据集).预期结果应为行号 1,2,3,4,5,6,12,13,14,15,16,17,21,22。

最佳答案

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

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

关于mysql - 使用 group by 的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965490/

相关文章:

php - 如何防止 PHP 中的 SQL 注入(inject)?

python - Pandas - 如果满足条件则进行分组

mysql - 选择计算时间范围内的多个字段 - MYSQL

mysql - 如何在mysql中使用count(*) WHERE IN

sql - 分组多行

SQL Query 获取常用记录

当计算多列中的出现次数时,mysql错误 "Operand should contain 1 column(s)"

php - 如何从 HTML 表和数据库中删除查询?

mysql select IN 如果id不存在则返回null

mysql - Rails 复杂 SQL