2017-12-31 58 views
0

나는 week1, week2와 같은 모든 행을 합친 다음 결과 합계 row2와 행 1, 행 row3과 행 2를 합치고 싶습니다. 어떻게하면됩니까? 잠시 루프에서Mysql sum row before

는 데이터베이스 : 지금

Database

결과 :

Outcome right now

나는 수를 wan't :

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> 
+0

편집 질문 및 샘플 데이터와 원하는 결과를 제공합니다. –

+0

https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql- 쿼리 – Strawberry

답변

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 } ?> 
+1

그 트릭을 했어, 덕분에 –

+0

@ jon_doe 그 대답은 당신이 그것을 허용으로 표시 기억 도움이 - 감사합니다 – ADyson