mysql 如何用最少的php编码使用where条件回显不同列的总和值?

bihw5rsg  于 2023-08-02  发布在  Mysql
关注(0)|答案(1)|浏览(81)

我已经建立了学校考试成绩数据库,它包括不同的科目标志,即化学1,化学2的8个考试。我成功地回显了个人马克值在同一页上通过选择类节和主题下拉菜单的提交按钮。我想显示的累积结果,例如通过百分比,平均为男性,女性,总为所有这8个考试在同一页上。
我可以通过这些类型的代码做到这一点

$ab50query_am = "SELECT * FROM test_2324 where (chem1_1 >50 AND chem1_1<81) AND cls='$cls_show' AND sex='M' AND (section='$sect_show' )";
$resab50=mysqli_query($db,$ab50query_am);
$ab50val = mysqli_num_rows($resab50);

字符串
为此,我需要为每个类别和考试使用更多的编码。有没有数组类型的PHP脚本可以实现这一点。等待救援

uqjltbpv

uqjltbpv1#

我认为使用数组、循环和聚合可以帮助您实现这一点。比如说你声明/初始化你的数组像这样...

$exams = array('chem1_1', 'chem1_2', 'chem2_1', 'chem2_2', 'chem3_1', 'chem3_2', 'chem4_1', 'chem4_2');
$categories = array('M', 'F', 'Total');
$totals = array_fill_keys($categories, 0);
$counts = array_fill_keys($categories, 0);

字符串
然后你可以这样循环

$whereCondition = "(cls='$cls_show' AND section='$sect_show') AND (";
foreach ($exams as $index => $exam) {
    if ($index !== 0) {
        $whereCondition .= " OR ";
    }
    $whereCondition .= "($exam > 50 AND $exam < 81)";
}
$whereCondition .= ")";

$query = "SELECT sex, COUNT(*) AS count, AVG((chem1_1 + chem1_2 + chem2_1 + chem2_2 + chem3_1 + chem3_2 + chem4_1 + chem4_2) / 8) AS average,
          (SUM(chem1_1 > 50 AND chem1_1 < 81) + SUM(chem1_2 > 50 AND chem1_2 < 81) + SUM(chem2_1 > 50 AND chem2_1 < 81) + SUM(chem2_2 > 50 AND chem2_2 < 81) +
           SUM(chem3_1 > 50 AND chem3_1 < 81) + SUM(chem3_2 > 50 AND chem3_2 < 81) + SUM(chem4_1 > 50 AND chem4_1 < 81) + SUM(chem4_2 > 50 AND chem4_2 < 81)) AS pass_count
          FROM test_2324 WHERE $whereCondition GROUP BY sex";
$result = mysqli_query($db, $query);

while ($row = mysqli_fetch_assoc($result)) {
    $category = $row['sex'];
    $count = $row['count'];
    $passCount = $row['pass_count'];

    $totals[$category] += $passCount;
    $counts[$category] += $count;
}

$passPercentage = array();
$average = array();
foreach ($categories as $category) {
    $passPercentage[$category] = ($totals[$category] / ($counts[$category] * count($exams))) * 100;
    $average[$category] = $totals[$category] / $counts[$category];
}


然后,您可以根据需要在同一页面上回显这些值。

相关问题