我想对第1周,第2周等所有行求和,然后我要在结果中将第1行与第2行相加,将第3行与第2行相加,依此类推。
我能怎么做?在while循环中
数据库:
Database
现在的结果:
Outcome right now
我不想成为:
Wanted outcome
$query ="SELECT
week,
sum(field1) AS field1,
sum(field2) AS field2,
sum(field3) AS field3
FROM table_test
GROUP BY week
ORDER BY week ASC";
$result = mysqli_query($conn ,$query);
<table>
<thead>
<tr>
<th>Week</th>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row['week'];?></td>
<td><?php echo $row['field1'];?></td>
<td><?php echo $row['field2'];?></td>
<td><?php echo $row['field3'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
最佳答案
您可以在while循环中保留一组运行总计,并将当前行字段的值添加到每个相关总计中。然后显示当前总数而不是行值。
像这样:
$totals = array(0, 0, 0);
while($row = mysqli_fetch_assoc($result)) {
$totals[0] += $row['field1'];
$totals[1] += $row['field2'];
$totals[2] += $row['field3'];
?>
<tr>
<td><?php echo $row['week'];?></td>
<td><?php echo $totals[0];?></td>
<td><?php echo $totals[1];?></td>
<td><?php echo $totals[2];?></td>
</tr>
<?php } ?>