查找避免空数据的列的平均值


find average of a column avoiding null data

我有这个表格:'grade',列如下:"student_id"得分"

要称呼"student_id"我使用

<?php echo $myData['student_id'];?>

调用"分数"我使用

<?php echo $myData['score'];?>

当我想称列的平均值为"分数"时,我使用

$query="Select AVG(score) as average FROM grade";    
$result_array=mysql_query($query); 
$average= mysql_fetch_array($result_array);

问题是,列score中有null数据,平均值将其计为0

因此,以下是从列分数中获取的示例数据:问题:

'10', '10', '10', '' , '10' will give average of 8.

我想要的是这样的:

'10', '10', '10', '' , '10' will give average of 10

任何帮助如何解决这个问题?

你可以有一个简单的if语句来计算''(null),然后从数据大小中减去它

for (i =0; i < resultarray.length; i++){
   if (resultarray[i] == ''){
    nullcounter++;
   } else { 
    sum += sum; 
  } 
} 
average = sum /(resultarray.length - nullcounter);

不知道为什么会给出这样的结果,因为 SUM、COUNT、AVG 等聚合函数默认丢弃 NULL 值。

无论如何,您可以尝试这样做以确保安全:

SELECT AVG(score) as average 
FROM grade
WHERE score IS NOT NULL