我试图想出一个SQL查询来计算前五个用户,这些用户的答案成功率最高。我有一个查询可以检索回答最多问题的前五位用户,如果答案是正确的,则无关紧要
SELECT b.user_id,
Count(1) AS answers,
username
FROM score a
JOIN processedquestion b
ON a.attempt_id = b.attempt_id
JOIN users c
ON b.user_id = c.user_id
WHERE selected_answer IS NOT NULL
GROUP BY user_id
ORDER BY Count(1) DESC
LIMIT 5
我的查询前五位用户的答案最正确
SELECT b.user_id,
Count(1) AS correct_answers,
username
FROM score a
JOIN processedquestion b
ON a.attempt_id = b.attempt_id
JOIN users c
ON b.user_id = c.user_id
WHERE selected_answer = correct_answer
GROUP BY user_id
ORDER BY Count(1) DESC
LIMIT 5
我要做的是查询现在将按其所有答案的成功率百分比返回前五名用户。因此,如果用户只回答了一个问题并且它是正确的,那么它们将在查询中以100%的成功率返回。我正在使用的表是
ProcessedQuestions(attempt_id, user_id, question_id, attempt_datetime)
Score(score_id, attempt_id, correct_answer, selected_answer)
Users(user_id, first_name, last_name)
任何帮助表示赞赏
答案 0 :(得分:2)
您可以使用条件聚合。在MySQL中,使用avg()
:
SELECT b.user_id, username, count(*) as answers,
avg(selected_answer = correct_answer) as p_correct
FROM score a JOIN
processedquestion b
ON a.attempt_id = b.attempt_id JOIN
users c
ON b.user_id = c.user_id
WHERE selected_answer IS NOT NULL
GROUP BY user_id
ORDER BY p_correct DESC
LIMIT 5;