如何使用外部表编写子查询

时间:2015-11-11 12:47:38

标签: mysql subquery

我需要编写一个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)

它无法正常工作。

通常,我需要知道如何在子查询中使用外表。 有谁可以帮助我?

2 个答案:

答案 0 :(得分:1)

通常情况下,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);

答案 1 :(得分:0)

当您计算导致NOT NULL的语句时,您也可以制作嵌入式构造。 换一种说法。如果condition = true,则IF(condition, 1, NULL)评估为1,否则评估为NUL L. COUNT函数计算NOT NULL个输入并给出结果。 您可以将a.ac=0 / a.ac=1替换为任何其他条件。

SELECT
    month(a.ct)AS month,
    (count(if(a.ac=0,1,NULL)))AS oldAccount,
    (count(if(a.ac=1,1,NULL)))AS newAccount
FROM
    accounts a

GROUP BY
    month(a.ct)
相关问题