0

My sql codes execute but I don't know how get the difference of purchase_request total_qty and purchase_order qty.

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

I want to code just like this, but I don't know how to mix it in my codes.

a.total_qty-b.qty as balance 

And this is my codes

<?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>";

    ?>

2 Answers2

0

Did you try this?

    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

Edit: I got it, what you need is to aggregate your quantities and then do the math

mucio
  • 7,014
  • 1
  • 21
  • 33
-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
mucio
  • 7,014
  • 1
  • 21
  • 33
  • the counter 100001 balance = 120 which is wrong, but the counter 100004 = 40 which is correct. Why is that? but this is my answer a.total_qty - sum(b.qty) as balance and both counter = is correct. If it is right? – user2991590 Nov 14 '13 at 11:17
  • this will give you cartesian join between Purchase_Order and purchase_request when there are multiple row with the same counter – mucio Nov 14 '13 at 12:15