简体   繁体   English

mysql计数结果状态正确并按用户ID分组

[英]mysql count result status correct and group by user id

I made a query in which there are result being compared from a pre defined answers table to the answers which a user enters for multiple questions . 我进行了一个查询,其中将结果从预定义的答案表与用户针对多个问题输入的答案进行比较。 The problem is now i want to get the total score (which i can calculate according to status correct ) of each user . 现在的问题是我想获得每个用户的总分(我可以根据正确的状态进行计算)。 The following query gives me all the users data with status of each question's answer to be correct or not . 以下查询为我提供了所有用户数据,其中每个问题的答案的状态是否正确。

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 

If i add GROUP BY user_id in the end it also groups the result by user_id But how to count all the status correct so that i can get the total number of correct answers count . 如果我最后添加GROUP BY user_id ,它也将结果按user_id分组。但是如何correct计数所有状态,以便我可以得到正确答案总数。

First of all, you're misusing, and proposing to misuse, GROUP BY . 首先,您正在滥用,并建议滥用GROUP BY When you use it correctly, every column in your result set is either also mentioned in the GROUP BY clause or is an aggregate column. 当正确使用它时, GROUP BY子句中还会提到结果集中的每一列,或者是聚合列。 Please read up on GROUP BY and use it correctly or you'll have a hard time troubleshooting your queries. 请仔细阅读GROUP BY并正确使用它,否则您将很难对查询进行故障排除。

Secondly, you can wrap your query up in an outer aggregate query and do the summary. 其次,您可以将查询包装在外部汇总查询中并进行汇总。 This kind of thing should work, as long as the query in your question works. 只要您的问题中的查询有效,这种事情就应该起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM