我将此作为我的函数来整理多个值(在我的情况下是平均值),我已经可以输出最高的值(平均值)。我现在要做的不是输出最高值(平均值)而是输出包含最高值(平均值)的列名。我尝试了mysql_fetch_field()
,但它为我输出了null
。另外,有没有办法计算average($averagesa)
?
<?php
usort($averagesa, function($a, $b) { // $averagesa contains several averages
if ($a['avg'] == $b['avg']) { // from multiple queries
return 0;
}
return ($a['avg'] > $b['avg']) ? -1 : 1;
});
$highesta = $averagesa[0];
echo $highesta['avg']; // highest average value
?>
这是示例查询,我想输出列(即C1.1),如果它包含最高的平均值
<html>
<table>
<tr><th>Campus</th>
<th>No. of Staff</th>
<th>C1.1</th>
<th>C1.2</th>
<th>C1.3</th>
<th>C1.4</th>
<th>C1.5</th>
<th>C1.6</th>
<th>C2.1</th>
<th>C2.2</th>
<th>C2.3</th>
<th>C3.1</th>
<th>C3.2</th>
<th>C3.3</th>
<th>C3.4</th>
<th>AVERAGE</th>
</tr>
<tbody>
<tr>
<td>MAIN 1 - CABEIHM</td>
<?php
$querya1 = ("SELECT ROUND(AVG(Compv11),2), dept_code, camp_code
FROM performance
INNER JOIN employment
ON employment.emp_code=performance.emp_id
AND employment.dept_code=performance.dept_id
WHERE empg_code=1 AND dept_id=3");
$resulta1 = mysql_query($querya1) or die(mysql_error());
// Print out result
while($rowa1 = mysql_fetch_array($resulta1))
{
$averagesa[1] = array(
'avg' => $rowa1['ROUND(AVG(Compv11),2)'],
'empg_code' => 1,
'dept_id' => 3,
'dept_code' => $rowa1['dept_code'],
'camp_code' => $rowa1['camp_code']
);
echo "".$rowa1['ROUND(AVG(Compv11),2)'];
}
?>
答案 0 :(得分:0)
考虑一个纯SQL解决方案,它输出对应于最高平均值的 dept_code 和 camp_code 。将此单行值分配给PHP数组。此外,查询中添加了GROUP BY
子句,以确保符合ANSI标准的聚合。
SELECT t.dept_code, t.camp_code, t.avg_comp
FROM
(SELECT ROUND(AVG(Compv11),2) as avg_comp, dept_code, camp_code
FROM performance
INNER JOIN employment
ON employment.emp_code=performance.emp_id
AND employment.dept_code=performance.dept_id
WHERE empg_code=1 AND dept_id=3
GROUP BY dept_code, camp_code) as t
ORDER BY t.avg_comp DESC
LIMIT 1