我需要编写一个 MySQL 查询来获取每个月的帐户数量、新帐户数量和旧帐户数量。 旧帐户的条件描述为 cond1。
我已经尝试过:
select month(a.ct) as month,
count(select id from a where cond1) as oldAccount,
count(select id from a where !cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct)
它并不完全有效。
一般来说,我需要知道如何在子查询中使用外表。 谁能帮助我吗?
最佳答案
通常,count()
会进入子查询内部:
select month(a.ct) as month,
(select count(id) from a where cond1) as oldAccount,
(select count(id) from a where !cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct);
但是,外部查询中有一个聚合,因此这有点复杂。您的关联条件大概是在 ID 上而不是在月份上。这种不一致会影响上面的查询。
最好的方法可能是将其表达为join
,但这可能取决于条件。否则,您可以使用子查询:
select month(a.ct) as month,
sum(oldAccount), sum(newAccount)
from (select a.*,
(select count(id) from a where cond1) as oldAccount,
(select count(id) from a where !cond1) as newAccount
from accounts a
where ~conditions~
) t
group by month(a.ct);
编辑:
如果通过 a
,您想要外部 accounts
表,则只需使用条件聚合:
select month(a.ct) as month,
sum(cond1) as oldAccount,
sum(!cond1) as newAccount
from accounts a
where ~conditions~
group by month(a.ct);
关于mysql - 如何使用外表编写子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33650863/