两个mysql子查询之间的减法

时间:2016-08-19 10:57:41

标签: mysql

我试图减去两个子查询。下面列出了两个表

COM_PAYMENTS

+++++++++++++++++++
tender_id | amount
+++++++++++++++++++
   10     | 200
   10     | 345
   22     |  18
   25     |  45

COM_RECEIPTS

+++++++++++++++++++
tender_id | amount
+++++++++++++++++++
   10     | 10
   10     | 15
   22     | 13

我想在查询中实现的是首先我需要找到COM_PAYMENTS和COM_RECEIPTS的tender_id总和,并且需要从COM_RECEIPTS的总量中减去COM_PAYMENTS的总量。

Example: The out put in this case should be:

tender_id | Total

    10      520 (200 + 345 = 545, 10 + 15 = 25, 545 - 25= 520)
    22      5   (18 - 13)
    25      45 ( Since COM_PAYMENTS doesnt have any recrds)

这就是我所尝试过的,但COM_RECEIPTS中的数据只显示总数,而其他数据则没有减去显示空白:

(select
SUM(com_payments.amount)
FROM com_payments
WHERE view_sales_report.tender_id = com_payments.tender_id) -
(select
SUM(com_receipts.rec_amt)
FROM com_receipts
WHERE view_sales_report.tender_id = com_receipts.tender_id)

3 个答案:

答案 0 :(得分:3)

继续前进,我建议您只有一个表,它记录所有交易 - 付款和收据 - 带有transaction_id和记录交易类型的列。

答案 1 :(得分:0)

这可能是你需要的东西:

SELECT tender_id, SUM(amount) AS amount
FROM (
    SELECT tender_id, SUM(amount) AS amount
    FROM COM_PAYMENTS
    GROUP BY tender_id
    UNION ALL
    SELECT tender_id, SUM(amount * -1) AS amount
    FROM COM_RECEIPTS
    GROUP BY tender_id
  ) a
GROUP BY tender_id  

答案 2 :(得分:0)

SELECT SUM(DISTINCT pa.amount)-IFNULL(SUM(DISTINCT re.amount) , 0) FROM com_payments pa
LEFT OUTER JOIN com_receipts re ON pa.`tender_id` = re.`tender_id` GROUP BY pa.tender_id