无法获取php mysql表中一列中每一行的总和

时间:2018-09-23 15:35:10

标签: php mysql sum

enter image description here enter image description here我有一个数据库表,该表具有多个列和多行数据。我想获取每一行中所有数据的所有数据的总和,并将其放置在col“总计”中。但是,总计显示在每一行中,而不是每一行的总计中。

我正在显示以下代码

<?php 
include 'config.php';
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$add=mysqli_query($con,"SELECT Col1,    Col2,   Col3,   Col4,   
sum(Col1 +  Col2 +  Col3 +  Col4) AS Total, SUM(Col1), SUM(Col2), 
SUM(Col3), SUM(Col4)
from DistrictData WHERE District = 'District1' ");
while($row=mysqli_fetch_array($add))
{
$Total = $row['Total'];
$SUM1=$row['SUM(Col1)'];
$SUM2=$row['SUM(Col2)'];    
$SUM3=$row['SUM(Col3)'];
$SUM4=$row['SUM(Col4)'];
$Total2= $SUM1 + $SUM2+ $SUM3+ $SUM4  ;
}
}
$sql="SELECT * FROM DistrictData WHERE District = 'District1'"; $counter = 0;
$result = $con->query($sql);
?>
<body>
<table >
<tr>
<td>Sr No.</td>
<td>Deptt</td>
<td>Data Description</td>
<td>Unit</td>
<td>Year</td>
<td>Blocks in District</td>
</tr>
<tr>
<td>Total</td>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
<?php
while($rows = $result->fetch_assoc())
{
?>
<tr> 
<td><?php echo ++$counter; ?></td>
<td><?php echo $rows['Data']; ?></td>
<td><?php echo $rows['Description']; ?></td>
<td><?php echo $rows['Unit']; ?></td>
<td><?php echo $rows['Year']; ?></td>
<td> <?php echo $Total ?></td>
<td><?php echo $rows['Col1']; ?></td>
<td><?php echo $rows['Col2']; ?></td>
<td><?php echo $rows['Col3']; ?></td>
<td><?php echo $rows['Col4']; ?></td>
</tr>
<?php
}
?>
<tr>
<td>Total:</td>
<td> <?php echo $Total2 ?></td>
<td> <?php echo $SUM1 ?></td>
<td> <?php echo $SUM2 ?></td>
<td> <?php echo $SUM3 ?></td>
<td> <?php echo $SUM4 ?></td>
</tr>
</table>
<?php    
$con->close();
?>  

Output of the code

请建议对代码进行任何更改,以便我可以在“总计列”中获取每一行的总和。

预先感谢

3 个答案:

答案 0 :(得分:1)

在每个Sum()之后使用同盟。 当您从while循环中删除总计时,您将获得最后的结果。 在第二查询下执行第一个查询,并将ID作为参数传递。

while($row = mysqli_fetch_array($query)){

   $total_query = mysqli_query($con,"SELECT Col1,    Col2,   Col3,   Col4,   
   SUM(Col1 +  Col2 +  Col3 +  Col4) as Total from DistrictData WHERE id='row[yourID]'");

   $total_result = mysqli_fetch_array($total_query);

   NOW you can populate your data here

}

希望这会对您有所帮助。

答案 1 :(得分:0)

将此查询用于列元素的行总和

 SELECT Col1+Col2+Col3+Col4 as I_want_this_figure from DistrictData

答案 2 :(得分:0)

请注意,规范化的环境通常看起来更像这样……

sr_no district_block val
    1              1   5
    1              2   6
    1              3   5
    1              4   8
    2              1 226
    2              2 112
    2              3   4
    2              4   5
    3              1   2 
    3              2   7
    3              3   3
    3              4   8

......,其中(sr_no,district_block)是主键的组成部分