0

SQL コードは実行されますが、 purchase_request total_qty と purchase_order qty の差を取得する方法がわかりません。

テーブル 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    | 

このようにコーディングしたいのですが、コードに混在させる方法がわかりません。

a.total_qty-b.qty as balance 

そして、これは私のコードです

<?php
    $mysqli = new mysqli("localhost", "root", "", "test");

        $result = $mysqli->query("
        select a.counter,a.total_qty from purchase_request a inner join purchase_order b on a.counter= b.counter group by a.counter
        ");
        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>";

    ?>
4

2 に答える 2

0

これを試しましたか?

    select a.counter,
           a.total_qty,
           a.total_qty - b.qty balance 
      from (select counter,
                   sum(total_qty) total_qty
              form purchase_request
          group by counter) a 
inner join (select counter,
                   sum(qty) qty
              from purchase_order 
          group by counter) b 
        on a.counter= b.counter 
  group by a.counter

編集:わかりました。必要なのは、数量を集計してから計算することです

于 2013-11-14T10:34:44.300 に答える
-1
    select a.counter,
           a.total_qty,
           sum(a.total_qty) - sum(b.qty) as balance 
      from purchase_request a 
left inner join purchase_order b 
        on a.counter= b.counter 
  group by a.counter
于 2013-11-14T11:01:43.610 に答える