如何从这张表中得到总和?

时间:2015-08-30 07:42:30

标签: sql sql-server

如何从两个表中得到总和?

  1. res_transactions
  2. TRANS_ADD
  3. 查询:

    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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 :(得分: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;

这是你的预期输出.... ????