2013-11-14 123 views
0

我的sql代碼執行,但我不知道如何得到purchase_request total_qty和purchase_order數量的差異。獲取兩個不同表格中兩列的差異?

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

    ?> 

回答

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 

編輯:我知道了,你需要的是收集您的數量,然後做數學

+0

它的工作原理,但餘額爲40,我需要得到的3總和100001櫃檯的數量和減去total_qty。我應該得到20作爲餘額 – user2991590

+0

我已更新查詢 – mucio

+0

它變得越來越差,$ row ['total_qty']丟失,100001的餘額變爲120:/ – user2991590

-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 
+0

計數器100001餘額= 120這是錯誤的,但計數器100004 = 40這是正確的。這是爲什麼?但這是我的答案a.total_qty - sum(b.qty)作爲餘額,並且counter =是正確的。如果它是正確的? – user2991590

+0

這會給你在Purchase_Order和purchase_request之間的笛卡爾連接,當有多行具有相同的計數器時 – mucio

相關問題