我做了一个查询,其中有一个结果从预先定义的答案表与用户为多个问题输入的答案进行比较。问题是现在我想获得每个用户的总分(我可以根据状态正确计算)。以下查询为我提供了所有用户数据,其中每个问题的答案状态是否正确。
SELECT qa.question_id, qa.test_id, uta.user_answer,uta.user_id, qa.type,
qa.answers correct_answer,
CASE WHEN uta.user_answer = qa.answers THEN 'correct' ELSE 'incorrect' END
AS status
FROM questions_answer qa
LEFT JOIN
(
SELECT user_id, type, test_id, question_id,
GROUP_CONCAT(answers ORDER BY answers) AS user_answer,
timestamp from user_test_answers
WHERE test_id = '1'
GROUP BY user_id, question_id
) uta
ON qa.question_id = uta.question_id
where qa.test_id=1
如果我最后添加GROUP BY user_id
,它还会按user_id
对结果进行分组但是如何计算所有状态correct
以便我可以获得正确答案的总数。
答案 0 :(得分:1)
首先,你是在滥用,并提议滥用,GROUP BY
。正确使用它时,结果集中的每一列也会在GROUP BY
子句中提及,或者是聚合列。请阅读GROUP BY
并正确使用它,否则您将难以排查查询。
其次,您可以将查询包装在外部聚合查询中并执行摘要。只要您的问题中的查询有效,这种事情就可以了。
SELECT user_id, test_id,
100 * SUM(status='correct') / COUNT(status) AS percent_correct,
100 * SUM(status='incorrect') / COUNT(status) AS percent_incorrect
FROM (
/* your entire query from your question */
) AS results
GROUP BY user_id, test_id
ORDER BY user_id, test_id