我目前正在尝试生成欠会员和会员的付款清单。
statistics
稳定栏包含以下列:
id, revenue, member, referral, date
这是我当前的代码:
SELECT
member,
SUM(revenue) AS payment,
(SELECT SUM(revenue) FROM statistics WHERE referral = member AND date BETWEEN '04/01/2019' and '04/31/2019') AS aff_earnings,
(SELECT paypal FROM members WHERE id = member) AS paypal
FROM
statistics
WHERE
date BETWEEN '04/01/2019' and '04/31/2019'
GROUP BY
member
对于member
,payment
和paypal
,我得到了正确的结果。但是,aff_earnings
将返回null
的所有结果。
对于每个member
,我想获取他们当月产生的总收入。显示为payment
是正确的。
但是,我还想获取他们的任何引荐所产生的总金额。可以通过在referral
列中搜索该成员的ID来找到其推荐人。
我正在尝试将该金额输出为aff_earnings
,但不确定如何将其返回为null
:/
答案 0 :(得分:1)
您可以使用相关的子查询,但是如果它们不返回任何行,则结果为NULL
。但是,这里没有发生这种情况,因为子查询是没有GROUP BY
的聚合查询,因此它总是返回一行。
因此,请使用COALESCE()
:
SELECT s.member, SUM(s.revenue) AS payment,
(SELECT COALESCE(SUM(s2.revenue), 0)
FROM statistics s2
WHERE s2.referral = s.member AND
s2.date >= '2019-04-01' AND
s2.date < '2019-05-01'
) AS aff_earnings,
(SELECT m.paypal
FROM members m
WHERE m.id = s.member
) AS paypal
FROM statistics s
WHERE s.date >= '2019-04-01' AND
s.date < '2019-05-01'
GROUP BY s.member;
注意: