0

我的 sql 代码执行但我不知道如何获得 purchase_request total_qty 和 purchase_order 数量的差异。

表采购_订单

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

Table 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 回答