2015-08-30 62 views
0

如何從兩個表中獲得總和?如何從該表中獲得總和?

  1. res_transactions
  2. TRANS_ADD

查詢:

select 
    tranid, Qty, Price 
from 
    res_transactions 
where 
    order_no = '16104' 
    and tranid = '506060' 
order by 
    tranid asc 

select 
    FTRN, Qty, Price 
from 
    TRANS_ADD 
where 
    FTRN = '506060' 

請參考附件快照更多信息

的例外輸出

Qty * Price 

總價應該是:13.6

enter image description here

回答

1
select sum(result) as sumresult from 
    (select Qty * Price as result from res_transactions where order_no='16104' and tranid='506060' 
    union all 
    select Qty * Price as result from TRANS_ADD where FTRN='506060' 
    )t 
2

從res_transactions得到總和:

SELECT TRANID AS ID, SUM(QTY*PRICE) AS TOTAL 
FROM RES_TRANSACTIONS WHERE ORDER_NO='16104' AND TRANID='506060' 
GROUP BY TRANID 

同爲TRANS_ADD:

SELECT FTRN AS ID, SUM(QTY*PRICE) AS TOTAL 
FROM TRANS_ADD WHERE FTRN='506060' 
GROUP BY FTRN 

所以,如果你想找到這兩個值的總和,你可以使用union all關鍵字。 請勿使用union,因爲它會刪除重複的行。

SELECT ID, SUM(TOTAL) AS TOTAL FROM (
    SELECT TRANID AS ID, SUM(QTY*PRICE) AS TOTAL FROM RES_TRANSACTIONS WHERE ORDER_NO='16104' AND TRANID='506060' GROUP BY TRANID 
    UNION ALL 
    SELECT FTRN AS ID, SUM(QTY*PRICE) AS TOTAL FROM TRANS_ADD WHERE FTRN='506060' GROUP BY FTRN 
) TBL 
0

試試這個

SELECT Qty,Price,Qty*Price 
FROM TRANS_ADD T,res_transactions R 
WHERE T.FTRN=R.tranid 
AND T.FTRN=506060 
AND R.order_no = 16104; 

這是你期望的輸出.... ????