下面是我的代码,我试图计算单列中的值的总和,即:SUM(sum) 作为总计,我想在输出表中将其打印为总计;但这部分代码没有产生预期的输出。
<?php
require_once('includes/connect.php');
$result = mysqli_query($con, "SELECT studentid, hw1, hw2, hw3, SUM(hw1+hw2+hw3) as sum, SUM(sum) as total FROM scores GROUP BY studentid");
echo "<table border='1'>
<thead>
<tr>
<th>StudentID</th>
<th>HW1</th>
<th>HW2</th>
<th>HW3</th>
<th>SUM</th>
</tr>
</thead>";
echo "<tfoot>
<tr>
<td>Total:</td>
<td> echo SUM(sum);</td>
</tr>
</tfoot>";
while ($row = mysqli_fetch_array($result))
{
"<tbody>
<tr>";
echo "<td>" . $row['studentid'] . "</td>";
echo "<td>" . $row['hw1'] . "</td>";
echo "<td>" . $row['hw2'] . "</td>";
echo "<td>" . $row['hw3'] . "</td>";
echo "<td>" . $row['sum'] . "</td>";
echo "
</tr>
</tbody>";
}
echo "</table>";
mysqli_close($con);
?>
我将感谢解决此问题的建议。 谢谢。
最佳答案
您的查询中的错误 SUM(sum) 作为总计
$result = mysqli_query($con, "SELECT studentid, hw1, hw2, hw3, SUM(hw1+hw2+hw3) as sum, SUM(sum) as total FROM scores GROUP BY studentid");
应该是这样的
$result = mysqli_query($con, "SELECT studentid, hw1, hw2, hw3, SUM(hw1+hw2+hw3) as sum FROM scores GROUP BY studentid");
关于mysql - mysql中如何计算单列多行之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820074/