我使用DW创建记录集,用于计算按医院名称分组的表中的百分比。我需要得到百分比的平均值(通过百分比的总和除以医院的数量)。我只有一张桌子。
mysql_select_db($database_localapconnect, $localapconnect);
$query_Recordset1 = "SELECT COUNT(IF(ap_intervalname = 'Less than or equal to 12 hours', ap_intervalname, NULL))/ COUNT(ap_intervalname) *100 AS 'percent' FROM maintble GROUP BY `hospitalname`";
$Recordset1 = mysql_query($query_Recordset1, $localapconnect) or die(mysql_error());
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
while($row_Recordset1 = mysql_fetch_array($Recordset1)) {
print_r( $row_Recordset1['percent'].'<br>');
}
print_r ($totalRows_Recordset1).'<br>' ;
echo sum($row_Recordset1['percent'])/$totalRows_Recordset1;
结果:
83.0189
98.0000
86.2745
68.0365
94.9686
78.4314
6
我收到以下错误:
致命错误:在第49行的C:\ wamp \ www \ ap_database \ Untitled-1.php中调用未定义的函数sum()
答案 0 :(得分:1)
PHP中不存在函数 sum 。如果您想要数组元素的总和,则应使用array_sum
但是,在这个特定的情况下,我认为在循环中总和更好,因为你已经访问了所有元素......
例如,像这样:
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
$sum = 0.0;
while($row_Recordset1 = mysql_fetch_array($Recordset1)) {
print_r( $row_Recordset1['percent'].'<br>');
$sum += $row_Recordset1['percent'];
}
print_r ($totalRows_Recordset1).'<br>' ;
echo $sum/$totalRows_Recordset1;
答案 1 :(得分:0)
最简单的方法是使用子查询:
SELECT avg(percent)
FROM (SELECT AVG(CASE WHEN ap_intervalname = 'Less than or equal to 12 hours' THEN 100.0
ELSE 0 END) AS percent
FROM maintble
GROUP BY `hospitalname`
) m;
答案 2 :(得分:0)
你在这行php代码中调用sum()
。
sum($row_Recordset1['percent'])/$totalRows_Recordset1; /* mistake */
但这没有意义。首先,$row_Recordset1['percent']
只是一个普通的旧数字。另外,php没有内置的sum()
函数。
如果您不想使用SQL进行该计算,则需要在记录集处理循环中添加值。
$sum = 0.0;
$count = 0;
while($row_Recordset1 = mysql_fetch_array($Recordset1)) {
$count ++;
$sum += $row_Recordset1['percent'];
print_r( $row_Recordset1['percent'].'<br>');
}
echo $sum / $count;
注意我明确地计算了行而不是依赖num_rows()
。这是有充分理由的;在某些情况下,num_rows()
在您阅读记录集之前是不可靠的。