php - 如果相同的 id 重复,如何获取总和

标签 php mysql sql

如果相同的 id 在 for 循环中重复,我试图对值进行求和

<?php 
    $tax = count($_POST['tax_id']);
    for($i=0;$i<$tax;$i++) { 
        $tax_id = $_POST['tax_id'][$i]; 
        $tax_amount = $_POST['amount'][$i];
        $sql = "SELECT * FROM `ca_taxmaster` where tax_comp = $tax_id ";
        $now = mysql_query($sql) or die(mysql_error()); 
        while($row1 = mysql_fetch_array($now)){
            $per = $row1['tax_Percent'];            
            $tax_calc = ($tax_amount*$per)/100;
            $sum_total += $tax_calc;
?>

<tr>
    <td class="text-right" colspan="5"><b><?php echo $row1['tax_type']; ?></b></td>
    <td class="text-right"></td>
    <td class="text-right"><?php echo $tax_calc;?></td>
</tr>

<?php } } ?>

我的输出就像 在 Gst 的税栏中,我有 sgst&cgst,如果我第二次选择,我需要 sgst&cgst 的总和

  No.   Job          Description    SAC Code        Tax       Amount
   0    teaching           desc1    sa001           GST     -   1000
   1    engineer           desc2    sac002    IGST-Master   -   2000
   2    doctor             desc3    sac003          GST     -   1000
                                               Sub-Total        Rs.4000
                                                    SGST        90
                                                    CGST        90
                                                    IGST        360
                                                    SGST        90
                                                    CGST        90
                                                   Total        Rs.4720

但我需要得到如果相同的 id 重复它应该对值求和

                                                    SGST        180
                                                    CGST        180
                                                    IGST        360
                                                   Total        Rs.4720

我的sql结构如下: sql table structure

如果还有其他方法,请帮助我。提前致谢

最佳答案

根据您共享的表结构,您可以使用以下查询替换您的查询:

SELECT sum(tax_Percent) 
FROM ca_taxmaster where tax_comp = $tax_id 
GROUP BY tax_type;

关于php - 如果相同的 id 重复,如何获取总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49448412/

相关文章:

php - 多个组织的系统设计

PHP - 从数据库获取数据到 JSON

mysql - 用户的群组对话 mysql select for messages

mysql - 具有多个运算符的 SQL WHERE 命令

email - 将外部 php 文件包含到 php 邮件正文中

php - Laravel 日志对多对多关系的修订

php - Laravel 5.4 中任何用户登录时喜欢和不喜欢的功能

python - SQLAlchemy 连接表并在每一行中插入新字段

mysql - 使用 CASE 条件作为结果值

java - Apache Derby 和 Java - 优化插入