查找行的平均值

时间:2017-01-26 11:05:42

标签: php mysql

我试图找到一组来自select的结果的平均值:

我已经找到了一排结果的平均值,但我需要找到平均值的平均值,但是我很难计算行数并进行数学运算。

这是我的PHP:

<?php
$dansql2 = "SELECT team_members.team_id, team_members.member_id, members.member_id, 
                    members.firstName, members.lastName, members.score_1, members.score_2, 
                    members.score_3, members.score_4, members.score_5, members.score_6, 
                    members.score_7, members.score_8
            FROM team_members 
                JOIN members
                    ON team_members.member_id = members.member_id
            WHERE members.dashboard_id = $dashboard_id 
              AND team_members.team_id = $teamSelect
            ORDER BY members.firstName ASC";


$danresult = $conn->query($dansql2);?>
<?php      
if ($danresult->num_rows > 0) {
    while($row = $danresult->fetch_assoc()) {

        $score1 = $row["score_1"];
        $score2 = $row["score_2"];
        $score3 = $row["score_3"];
        $score4 = $row["score_4"];
        $score5 = $row["score_5"];
        $score6 = $row["score_6"];
        $score7 = $row["score_7"];
        $score8 = $row["score_8"];

        $sum = $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 + $score8;
        $totalAverage = $sum / 8;

        echo $totalAverage; 
    }
}
?>

所以我需要找到总平均值来自$ totalAverage变量。这打印出每个行分数的平均值,但我需要将$ totalAverage

抬高

1 个答案:

答案 0 :(得分:2)

你的意思是这样吗

<?php
$dansql2 = "SELECT team_members.team_id, team_members.member_id, members.member_id, 
                    members.firstName, members.lastName, 
                    members.score_1, members.score_2, 
                    members.score_3, members.score_4, 
                    members.score_5, members.score_6, 
                    members.score_7, members.score_8,
                    (members.score_1 + members.score_2 +
                    members.score_3 + members.score_4 + 
                    members.score_5 + members.score_6 +
                    members.score_7 + members.score_8 ) / 8 as membersAvg
            FROM team_members 
                JOIN members
                    ON team_members.member_id = members.member_id
            WHERE members.dashboard_id = $dashboard_id 
              AND team_members.team_id = $teamSelect
            ORDER BY members.firstName ASC";


$danresult = $conn->query($dansql2);

$allAvg = 0;
while($row = $danresult->fetch_assoc()) {
    $allAvg += $row['membersAvg'];
    echo $row['firstName'] . ' ' .$row['lastName'] . ' Avg = ' . $row['membersAvg']; 
}
echo 'Avg of Avgs = ' . $allAvg / $danresult->num_rows;
?>