简体   繁体   English

如何将聚合查询与不同联接结合在一起?

[英]How to combine aggregated queries with different joins?

I've been looking at this SO post and this jooq.org post , trying to figure out how to do my combined aggregations in MySQL , but not having much luck. 我一直在看这个SO帖子这个jooq.org帖子 ,试图弄清楚如何在MySQL中进行组合的聚合,但是运气不佳。

Here are my 2 queries: 这是我的两个查询:

select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, count(*) AS Agents
from Users u
join Agencies a
on u.AgencyID = a.ID
group by a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate
order by a.IsTestAgency, a.AgencyName;

Results: 结果:

在此处输入图片说明

and: 和:

select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, count(*) AS Certs
from Certificates c
join Agencies a
on c.AgencyID = a.ID
group by a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate
order by a.IsTestAgency, a.AgencyName;

Results: 结果:

在此处输入图片说明

You can see that the columns and columns' datatypes match. 您可以看到列和列的数据类型匹配。 I'd like to combine these into a single query and show the Agents count and the Certs count side-by-side, since those are the only 2 column values that are different in the result sets. 我想将它们组合成一个查询,并同时显示“ Agents计数和“ Certs计数,因为这是结果集中唯一的两个列值。

How is it done? 怎么做?

Is this what you want? 这是你想要的吗?

select a.*, 
       (select count(*)
        from users u
        where u.AgencyID = a.ID
       ) as users_count,
       (select count(*)
        from Certificates c
        where c.AgencyID = a.ID
       ) as certificates_count
from Agencies a
order by a.IsTestAgency, a.AgencyName;

You could do this by JOIN ing to tables of COUNT s: 您可以通过JOIN COUNT表来做到这一点:

select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, u.Agents, c.Certs
from Agencies a
join (select AgencyID, COUNT(*) as Agents from Users group by AgencyID) u on u.AgencyID = a.ID
join (select AgencyID, COUNT(*) as Certs from Certficates group by AgencyID) c on c.AgencyID = a.ID
order by a.IsTestAgency, a.AgencyName;

This removes the need to group by in the top query and also saves having to do two subquery counts for each row of the output. 这样就无需在顶部查询中进行group by ,也省去了对输出的每一行进行两次子查询计数的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM