简体   繁体   English

使用mysqli从数据库中选择,分组和求和结果

[英]Select, Group and Sum Result from Database using mysqli

I have a record with customerId, GroupId, amountContributed which is captured on a daily basis.Now I want to return a table showing the total amount contributed by a customer with the group id.My previous code is: 我有一个有customerId,GroupId,amountContributed的记录,该记录每天捕获一次,现在我想返回一个表,显示具有组id的客户贡献的总金额。我之前的代码是:

if(isset($_POST["searchVal"])){
//$searchText = $_POST["searchText"];
$sDate = $_POST["sDate"];
$eDate = $_POST["eDate"];
$query = mysqli_query($connection,"SELECT custid,grpid,amountContribute FROM tab_customer_dailycontribution WHERE cast(transactionDate as date) BETWEEN '$sDate' AND '$eDate'");
if($connection->affected_rows>0){
    $c =0;$con =0.00;

while($rw = mysqli_fetch_array($query)){
    $c++;?> 
    <tr>
    <td><?php echo $c;?></td>
    <td><?php echo $rw['custid'];?></td>
    <td><?php echo $rw['grpid'];?></td>
    <?php $con+=$rw['amountContribute']; ?>
    <td><?php echo number_format($con,2);?></td>
  <?php  } ;?>
   </tr>
   <tr>

The above give this table: 上面给出了这个表:

S/N CustomerID  Group ID    Total Contribution
    1   SC20151 SGC20151    700.00
    2   SC20151 SGC20151    500.00
    3   SC20151 SGC20151    500.00
    4   SC20152 SGC20151    500.00
    5   SC20152 SGC20151    500.00
    6   SC20152 SGC20151    500.00
    7   SC20152 SGC20151    500.00
    8   SC20152 SGC20151    500.00
    9   SC20152 SGC20151    500.00
    10  SC20152 SGC20151    500.00
    11  SC20152 SGC20151    500.00
    12  SC20152 SGC20151    500.00
    13  SC20152 SGC20151    500.00
    14  SC20153 SGC20152    1,000.00
    15  SC20153 SGC20152    1,000.00

So, i want the ouput to be like this table below: 因此,我希望输出如下表所示:

 SN        Customer ID      Group ID       Amount Conributed
    1         SC20152           SCG20151        5000
    2         SC20151           SCG20151        1200
    3         SC20153           SCG20152        2000 

Can someone help. 有人可以帮忙吗? I have used group by customerid,amountcontributed but not working. 我已经使用了按客户ID分组,已贡献金额但无法正常工作。

SELECT custid, grpid, SUM(amountContribute) AS sumAmountContribute
FROM tab_customer_dailycontribution 
WHERE CAST(transactionDate AS date) BETWEEN '$sDate' AND '$eDate'"
GROUP BY custid, grpid

will give you what you need. 会给你你所需要的。

When outputting, you will then have to change your array index: 输出时,您将不得不更改数组索引:

<?php echo $rw['sumAmountContribute']; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM