如何将Purchase_Order.QTY和Purchase_Request.QTY的总和作为余额?我的问题是,Purchase_Order表中有多个po_number,它们具有相同的计数器。
以下是我的表格,
我需要在purchase_order中获得计数器100001的总数量,所以我可以得到QTY purchase_order和QTY 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 |
这是我的示例OUTPUT
输出
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>";
?>
帮助?
答案 0 :(得分:0)
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 :(得分:0)
这是您的选择。
WHERE
counter is = to
Purchase_Request.counter
QTY
的结果以获得sum
QTY
进行比较,以确定您的订单是否可以填写。 这是一个选择。另一个建议是清理你的数据库。您也可以进行SQL连接。
答案 2 :(得分:0)
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
答案 3 :(得分:0)
您可以将表1和2连接到计数器编号,然后使用sql进行计算
mysql_query(“SELECT *,O.QTY
- R.QTY
AS difference
FROM`On Purchase_Order AS O LEFT OUTER JOIN Purchase_Request AS R ON O.counter = R.counter”);
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;