简体   繁体   English

一列的总和与另一列的计数之比

[英]Ratio of sum of one column by count of another column

I'm trying to count the number of passed quizzes, as per the following results table:我正在尝试根据以下结果表计算通过测验的数量:

在此处输入图像描述

So, we have 3 quizzes, and if the proportion of correct answers is >= 0.5, then it is passed.因此,我们有 3 次测验,如果正确答案的比例 >= 0.5,则通过。 If the answer is correct, the result column shows 1, otherwise it shows 0.如果答案正确,结果列显示 1,否则显示 0。

For example, quiz 1 has 5 questions, of which 3 are correct.例如,测验 1 有 5 个问题,其中 3 个是正确的。 Quiz 2 has 3 questions, of which 1 is correct.测验 2 有 3 道问题,其中 1 道是正确的。 Quiz 3 has 2 questions, both are correct.测验 3 有 2 个问题,都是正确的。

So, this user has passed 2 quizzes out of 3.因此,该用户通过了 3 次测验中的 2 次。

My expected result is: "2 quizzes out of 3 are passed."我的预期结果是: "2 quizzes out of 3 are passed." using MYSQL with PHP with something like:使用 MYSQL 和 PHP 类似的东西:

$number_of_quizzes = 'SELECT COUNT(DISTINCT quiz_id) FROM TABLE'

But, I'm struggling with the query to count the number of rows in the 'result' column and the sum of its values - per quiz.但是,我正在努力使用查询来计算“结果”列中的行数及其值的总和 - 每个测验。

Is this possible to do with MYSQL alone, or should the logic be transferred to PHP?这可能与 MYSQL 单独有关,还是应该将逻辑转移到 PHP? How?如何?

Can anyone help?任何人都可以帮忙吗?

Try this:尝试这个:

$quiz_list = 'SELECT DISTINCT quiz_id FROM TABLE'
$count = 0
$number_of_quizzes = 'SELECT COUNT(DISTINCT quiz_id) FROM TABLE'

foreach ($quiz as &$quiz_list) {
    $nb_quiz = 'SELECT COUNT(*) FROM TABLE WHERE quiz_id = ' . $quiz . '';
    $nb_correct = 'SELECT COUNT(*) FROM TABLE WHERE quiz_id = ' . $quiz . ' AND result = 1';
    $count += ($nb_correct / $nb_quiz > 0.5 ? 1 : 0);
}
$expected_result = $count . " quizzes out of " . $number_of_quizzes . " are passed.";

Of corse you have to change my SQL queries in string to real queries.当然,您必须将字符串中的 SQL 查询更改为实际查询。

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

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