gpt4 book ai didi

php - Mysql 总和之前的行

转载 作者:行者123 更新时间:2023-11-29 18:04:20 26 4
gpt4 key购买 nike

我想对第 1 周、第 2 周等中的所有行进行求和,然后我想在结果中将第 2 行与第 1 行求和,将第 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 } ?>

关于php - Mysql 总和之前的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48042544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com