我有一个包含 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
关于mysql - 使用 group by 的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965490/