使用php对一个科目的所有学生取平均值
我有一个包含一个主题的学生的SQL表。我想对这门学科的所有学生进行平均,如下所示:使用php对一个科目的所有学生取平均值,php,mysql,Php,Mysql,我有一个包含一个主题的学生的SQL表。我想对这门学科的所有学生进行平均,如下所示: 科目总数/学生总数 该表如下所示: Student ID : 1 ============= Maths : 40 Student ID : 2 ============= Maths : 60 Student ID : 3 ============= Maths : 90 Student ID : 4 ============= Maths : 0 因此,如果该学生的分数为0,则在计算平均值时忽略该
科目总数/学生总数
该表如下所示:
Student ID : 1
=============
Maths : 40
Student ID : 2
=============
Maths : 60
Student ID : 3
=============
Maths : 90
Student ID : 4
=============
Maths : 0
因此,如果该学生的分数为0,则在计算平均值时忽略该学生及其分数
<?php
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$db = new PDO("mysql:host=localhost; dbname=db;charset=utf8",'user','');
$sql = "SELECT * FROM Students";
$stmt = $db->query($sql);
while($data = $stmt->fetch(PDO::FETCH_OBJ)){
//How to take the mean of 1 subject for all students?
}
?>
首先修复这一行,以便……您只能获得大于0的分数
$sql = "SELECT * FROM students WHERE subjectscore > 0"; //assuming your column for scores is "subjectscore"
代码的其余部分要达到平均值,应该是
$stmt = $db->query($sql);
while($data = $stmt->fetch(PDO::FETCH_OBJ)){
$sumparts .= $data->subjectscore."+"; //Add a delimiter after every returned obj
}
print_r($sumparts); //For debug :to see which ones are selected
$sumarr = explode("+",$sumparts); // Convert the delimited string to array
$sum = array_sum($sumarr); //Get sum of values of array in this case the scores
$divisor = count($sumarr) - 1; //The minus 1 is necessary since well the delimited string will always have 1 extra key therefore making the count to count 1 more unnnecessary key
$total = $sum/$divisor; //Sum of all divided by the total number of objects
echo $total;
只是为了让你知道学生的分数为0,然后忽略这不适用于计算意味着你仍然包括他们,否则通过的学生越少,这个数字就越高。如果1个学生得到99分,其余9个学生得到0分,而你忽略他们。。。那么你的平均值是99%,这就是wrong@KevinGales确切地但是,如果学生没有参加考试,则0也为零。所以在这种情况下,我不想把学生也包括在内。例如,在上面的例子中,平均数中的学生人数将只有3名。如果学生参加了但得到了零,情况如何?他们是否也被视为缺席?问题是,如果学生缺席或没有参加,我们将添加“null”。好的,我现在知道了