Mysql总和之前的行

时间:2017-12-31 12:45:36

标签: php html mysql

我想在第1周,第2周等所有行的总和,然后我想在结果sum row2中使用第1行,将row3与第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>

1 个答案:

答案 0 :(得分:0)

您可以在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 } ?>