簡體   English   中英

如何獲得不同表中兩個字段的總和?

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

如何獲取Purchase_Order.QTY和Purchase_Request.QTY的總和作為余額? 我的問題是Purchase_Order表中有多個具有相同計數器的po_number。

下面是我的桌子,

我需要在purchase_order中獲得計數器100001的總QTY,因此我可以得到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    |

這是我的示例輸出

輸出值

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連接。

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

您可以將表1和2連接到計數器編號上,然后使用sql進行計算

mysql_query(“ SELECT *, O.QTY - R.QTY AS difference `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; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM