如何获取不同表中两个字段的总和


How to get the sum of two fields in different table?

如何获得Purchase_Order.QTY和Purchase_Request.QTY的总和作为余额?我的问题是Purchase_Order表中有多个具有相同计数器的po_number。

下面是我的表格,

我需要在purchase_order中获取计数器100001的总数量,以便我可以得到数量purchase_order和数量之间的差异purchase_request

表 Purchase_Order

counter | qty |
100001  | 10  |
100001  | 10  |
100001  | 10  |
100004  | 30  |

表Purchase_Request

counter | total_qty |
100001  |     50    |
100002  |     100   |
100003  |     50    |
100004  |     70    |

这是我的例子输出

输出

counter | total_qty | balance |
100001  |     50    |  20     |
100002  |     100   |  100    |  
100003  |     50    |  50     |
100004  |     70    |  40     |

这是我的剧本,

<?php
$mysqli = new mysqli("localhost", "root", "", "test");
    $result = $mysqli->query("
    ");
    echo'<table id="tfhover" cellspacing="0" class="tablesorter" style="text-transform:uppercase;" border="1px">
        <thead>
        <tr>
        <th></th>
    <th>counter</th>
    <th>QTY</th>
    <th>balance</th>
        </tr>
        </thead>';
        echo'<tbody>';
    $i=1;   
while($row = $result->fetch_assoc()){
    echo'<tr>
            <td>'.$i++.'</td>
            <td>'.$row['counter'].'</td>
            <td>'.$row['total_qty'].'</td>
            <td>'.$row['balance'].'</td>
        </tr>';
       }
    echo "</tbody></table>";
?>

帮助?

SELECT PR.Counter,pr.qty-po.qty as remainingqty FROM Purchase_Request pr LEFT JOIN (Select counter,sum(qty) from Purchase_Order group by counter)po ON pr.Counter=po.Counter
这里有

一个选项。

  1. 获取表 Purchase_Order WHERE 中的所有记录计数器是 = 到 Purchase_Request.counter
  2. 循环浏览QTY的结果以获得sum
  3. 将总和与主表中的QTY进行比较,以确定是否可以执行您的订单。

这是一种选择。另一个建议是清理数据库。您还可以执行 SQL 联接。

您可以在计数器号上连接表 1 和表 2,然后使用 sql 进行计算

mysql_query("选择 *, O.QTY - R.QTY 作为 Purchase_Order 中的difference 作为 O 左外连接Purchase_Request作为 R 在 O.计数器 = R.计数器");

SELECT 
O.id, 
O.QTY,
COALESCE(O.QTY - (SELECT R.QTY 
                 FROM Purchase_Request AS R
                 WHERE O.counter = R.counter)) AS difference 
FROM Purchase_Order AS O; 

try this

select a.counter,a.po_number,a.unit_cost,sum(a.qty)-b.qty as ramaining_order_qty
    from table a
    inner join table b on a.counter=b.counter 
    group by a.counter,a.po_number,a.unit_cost,b.qty