我进行查询,显示每个用户回答每个部门的问题数量,以及每个用户在回答该部门的问题时的错误百分比。
所以,我尝试这样的查询,
SELECT d.department_id, d.department_name as department,
a.username, COUNT(a.username)total,
( (COUNT(r.is_correct)*100) /
( SELECT COUNT(a.username) total
FROM qa_report r
LEFT JOIN tbl_user a ON (r.user_id = a.admin_id)
LEFT JOIN department d on (a.department_id = d.department_id)
WHERE d.department_name = 'Dept1' AND is_correct='yes'
)
) as correct_percent
FROM qa_report r
LEFT JOIN tbl_user a ON (r.user_id = a.admin_id)
LEFT JOIN department d on (a.department_id = d.department_id)
WHERE d.department_name = 'Dept1'
GROUP BY a.username
这是结果,
total
列是用户为该部门回答的问题回答的数量。
在此total
中,正确且错误的答案正在混合。
但是当我尝试计算每个部门的正确/不正确的百分比时,correct_percent
列仍然是错误的。
问题出在这一行,
( (COUNT(r.is_correct)*100) /
( SELECT COUNT(a.username) total
FROM qa_report r
LEFT JOIN tbl_user a ON (r.user_id = a.admin_id)
LEFT JOIN department d on (a.department_id = d.department_id)
WHERE d.department_name = 'Dept1' AND is_correct='yes'
)
) as correct_percent
我需要在这个地方获得每个用户的正确百分比,
(correct percent of answer*100)/total question that user answer
eg. John => total: 10, correct 5, incorrect 5, correct %=50%
我非常感谢任何建议。
答案 0 :(得分:1)
我现在可以解决这个问题。当我尝试计算百分比时,我错了。 这是有效的查询,
SELECT d.department_id, d.department_name as department,
a.username, COUNT(a.username)total,
( (COUNT(CASE WHEN r.is_correct='yes' THEN 1 END)*100) / ( COUNT(a.username)) ) as correct_percent,
( (COUNT(CASE WHEN r.is_correct='no' THEN 1 END)*100) / ( COUNT(a.username)) ) as incorrect_percent
FROM qa_report r
LEFT JOIN tbl_user a ON (r.user_id = a.admin_id)
LEFT JOIN department d on (a.department_id = d.department_id)
WHERE d.department_name = 'Dept1'
GROUP BY a.username
希望对某人有所帮助。