如何计算mysql中单个列的多行总和

时间:2013-12-28 22:29:06

标签: mysql

下面是我的代码我试图计算单个列中的值之和:SUM(sum)为总数,我想在输出表中打印为Total;但是那部分代码没有产生预期的输出。

<?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);
 ?>

我将非常感谢您提出解决此问题的建议。 感谢。

2 个答案:

答案 0 :(得分:1)

您的查询SUM(sum) as total

中存在错误
$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");

答案 1 :(得分:0)

如果值可能为NULL,并且您希望忽略这些值,那么您可能需要:

SELECT studentid, hw1, hw2, hw3,
       (coalesce(sum(hw1), 0) + coalesce(sum(hw2), 0) +coalesce(sum(hw3), 0)) as total
FROM scores
GROUP BY studentid;