如何将特定行的列中的记录与同一行中的答案进行求和

时间:2017-11-17 17:30:43

标签: php mysql row

如何将费用,公共汽车和零食以及结果总计显示在同一行?例如100 + 20 + 500 = 620。

数据

salary recurrent repairs_maint .....   TOTAL
=============================================
100       20      250    250  .....     620
==============================================
20   10  200      100    100.....      430
==============================================

PHP代码

<?php 
      $add=mysqli_query($conn,'SELECT SUM(salary),SUM(recurrent),SUM(repairs_maint),SUM(creditors) ,SUM(petty_cash) ,SUM(capital_expenses)from `monthly_expenditure`');
      while($row1=mysqli_fetch_array($add))
      {
        $mark=$row1['SUM(salary)'];
        $mark1=$row1['SUM(recurrent)'];
        $mark3=$row1['SUM(repairs_maint)']; 
        $mark4=$row1['SUM(creditors)'];
        $mark5=$row1['SUM(petty_cash)'];
        $mark6=$row1['SUM(capital_expenses)'];
     ?>

      <tr>
      <th></th>
      <th>Total  =</th>
        <th><?php echo $mark ?></th>
        <th><?php echo $mark1 ?></th>
        <th><?php echo $mark3 ?></th>
        <th><?php echo $mark4 ?></th>
        <th><?php echo $mark5 ?></th>
        <th><?php echo $mark6 ?></th>

2 个答案:

答案 0 :(得分:0)

你可以从这里开始:

id expense value
 1 FEES      100  
 1 BUS        20   
 1 SNACKS    500    
 2 FEES       20
 2 BUS        10  
 2 SNACKS    400  

答案 1 :(得分:0)

您的描述有点令人困惑。如果我理解正确,那么你想要为每个id加总所有给定的属性。以下查询可能有效:

select t.id,t.a as salary,t.b as recurrent,t.c as repairs_maint,
       t.d as creditors,t.e as petty_cash,t.f as capital_expenses
       (t.a + t.b + t.c + t.d + t.e + t.f) as total
from
(SELECT SUM(salary) as a,
      SUM(recurrent) as b,
      SUM(repairs_maint) as c,
      SUM(creditors) as d,
      SUM(petty_cash) as e,
      SUM(capital_expenses) as f
from monthly_expenditure
group by id) t
group by t.id;