在一个查询中加入2个表Mysql的计算

时间:2016-04-04 12:58:35

标签: mysql sum

我正在尝试确定如何在两个表之间进行求和减去字段。

在表1(com_payments)中,我会有,例如,tender_id,金额

在表2(流程)中,我会有,例如,tender_id,lc_amt_value

我想从com_payments(sumofamount)中扣除金额并将其总和。首先,main_section = supplier

然后使用该sumofamount我需要减去lc_amt_value(表进程),其中com_payments.tenderid = process.tender_id(TotalAmount)

Table example:

    com_payments
    ----------------------------------
    tender_id | amount     | main_section
    ----------------------------------
    |      1  | 300.00     |  supplier
    |      1  | 200.989    |  customer
    |      1  | 2300.900   |  supplier
    ----------------------------------

    process
    ----------------------------
    tender_id | lc_amt_value
    ----------------------------
    |   1 |        50.00
    |   2 |        126.00
    |   3 |        50.00
    ----------------------------


The results that I *want* are

    TOTALS
    ------------------------------------------
    | tender_id | sumofamount | TotalAmount 
    ------------------------------------------
    | 1         |  2600.900   |   2550.900 
    ------------------------------------------

1)首先需要从表com_payments中获取'amount'(sumofamount)的总和,其中main_section ='supplier' 2)其次从sumofamount我需要从表进程中减去lc_amt_value(比较是tender_id)

SELECT sum(amount) AS  sumofamount 
FROM com_payments vg
LEFT JOIN process f
select (f.lc_amt_value - sumofamount) As TotalAmount
ON f.tender_id = vg.tender_id

我没有得到任何输出。任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询:

SELECT vg.tender_id, 
       sum(amount) as sumofamount, 
       sum(amount) - lc_amt_value as totalamount
FROM com_payments as vg
JOIN (SELECT tender_id, sum(lc_amt_value) as lc_amt_value
      FROM process
      GROUP BY tender_id
) as t on vg.tender_id = t.tender_id
GROUP BY tender_id