选择子查询中的UNION问题

时间:2017-10-12 14:29:51

标签: mysql

在下面的代码中,如何在UNION中将MRR_Created与MRR_Destroyed结合使用,以便它只显示下一个数字?现在查询是正确的,但我不需要分别看到增加/减少。

 select account.email, account.vip, datediff(now(), account.date_created) AS Age,
(select sum(account_subscription.next_invoice_price) as ActiveMRR
from account_subscription
where account_subscription.status = 'active'
and account_subscription.acctid = account.acctid
) as MRR,
(select count(account_subscription.subid) as Churn
from account_subscription
where account_subscription.date_created between DATE_ADD(NOW(), INTERVAL -2880 MINUTE) and NOW()
and account_subscription.date_closed between DATE_ADD(NOW(), INTERVAL -2880 MINUTE) and NOW()
and account_subscription.acctid = account.acctid
) as Churn,

(select sum(account_subscription.next_invoice_price) as MRR
from account_subscription
where date(account_subscription.date_created) = date(curdate())
and account_subscription.acctid = account.acctid
) as MRR_Created,
(select sum(account_subscription.next_invoice_price) as MRR
from account_subscription
where date(account_subscription.date_closed) = date(curdate())
and account_subscription.acctid = account.acctid
) as MRR_Destroyed,

 concat("https://sitetest.com?ACCTID=",account.acctid) as URL

 from account
 where account.status = 'active'
 and (
account.type in ('affiliate', 'customer', 'customer_freetrial', 'customer_duplicate', 'customer_match')
or account.type is null
)
 group by account.acctid
 order by MRR desc

1 个答案:

答案 0 :(得分:0)

不确定你是否真的需要UNION。尝试替换

(select sum(account_subscription.next_invoice_price) as MRR
from account_subscription
where date(account_subscription.date_created) = date(curdate())
and account_subscription.acctid = account.acctid
) as MRR_Created,
(select sum(account_subscription.next_invoice_price) as MRR
from account_subscription
where date(account_subscription.date_closed) = date(curdate())
and account_subscription.acctid = account.acctid
) as MRR_Destroyed,

(select sum(account_subscription.next_invoice_price) as MRR
from account_subscription
where (date(account_subscription.date_created) = date(curdate())
or date(account_subscription.date_closed) = date(curdate()))
and account_subscription.acctid = account.acctid
) as MRR_Created,

希望这有帮助!