SQL SUM和比较

时间:2017-04-26 11:04:59

标签: mysql sum

我有两个数据库表:

***aff_purchases***

id | affiliate_id | payout
1  | 12           | 50.00 
2  | 12           | 10.00
3  | 12           | 50.00
4  | 12           | 10.00

***aff_payments***

id | affiliate_id | amount_paid   
8  | 12           | 50.00

我想返回所有联属会员ID的数组,其中'付款'总数为50或者超过会员ID的'amount_paid'。

我认为我需要将列合并在一起然后进行比较,但我很难理解如何。请看下面我的努力:

SELECT
     (SELECT SUM(amount_paid) FROM exp_cdwd_aff_payments AS pay WHERE pay.affiliate_id = 12) AS 'amount_paid'
     (SELECT SUM(payout) FROM exp_cdwd_aff_purchases AS pur WHERE pur.affiliate_id = 12) AS 'payout'
FROM 
     exp_cdwd_aff_payments AS pay
WHERE 
     payout > amount_paid

2 个答案:

答案 0 :(得分:1)

这里的一种方法是使用连接两个单独的子查询来查找支付和支付总额。然后,比较每个affiliate_id,看看是否符合您的要求。

SELECT
    t1.affiliate_id
FROM
(
    SELECT affiliate_id, SUM(amount_paid) AS amount_paid_total
    FROM aff_payments
    GROUP BY affiliate_id
) t1
LEFT JOIN
(
    SELECT affiliate_id, SUM(payout) AS payout_total
    FROM aff_purchases
    GROUP BY affiliate_id
) t2
    ON t1.affiliate_id = t2.affiliate_id
WHERE COALESCE(t2.payout_total, 0) > t1.amount_paid_total + 50

请注意,有付款但尚未付款的关联企业不会出现在结果集中。

答案 1 :(得分:0)

问题是您无法使用SELECTWHERE中定义的别名。在大多数数据库中,您将使用CTE或子查询。但是,MySQL不支持CTE,它会对子查询施加开销(通过实现它们)。

因此,MySQL重载了HAVING子句,允许它在非聚合查询中使用。您可以使用HAVING

执行所需操作
SELECT a.affiliate_id,
       (SELECT SUM(cap.amount_paid) FROM exp_cdwd_aff_payments cap WHERE cap.affiliate_id = a.affiliate_id) AS amount_paid
       (SELECT SUM(pur.payout) FROM exp_cdwd_aff_purchases pur WHERE pur.affiliate_id = a.affiliate_id) AS payout
FROM affiliates a
HAVING payout > amount_paid;

以上假设您的表格每affiliate_id行一行。它通过相关子查询使用它。另请注意表名别和限定列名的使用。