Leo
Leo

Reputation: 3872

MySQL - how to sum counts by group

I have three tables connected with the following relation:

"agency" 1-n "agent" 1-n "ad" 
(agency has many agents and each agent has many ads)

I want to get a list of ad counts by agency, like this:

agency_name   |   ad_count
---------------------------
agency 1      |     15
agency 2      |     25
agency 3      |     0

Where even agencies with 0 ads would be shown. Is this possible? Thanks a lot!

Upvotes: 0

Views: 232

Answers (3)

Saharsh Shah
Saharsh Shah

Reputation: 29071

Try this:

SELECT a.agencyname, IFNULL(b.adcnt, 0) adcount  
FROM agency 
LEFT JOIN (SELECT a.agencyid, SUM(adcnt) adcnt 
           FROM agent a 
           INNER JOIN (SELECT agentid, COUNT(agentid) adcnt 
                       FROM ad 
                       GROUP BY agentid
                      ) b ON a.agentid = b.agentid 
           GROUP BY agencyid) b ON a.agencyid = b.agencyid

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74118

SQL Fiddle

select agency.agency_name, count(ad.id)
from agency
left join agent on agent.agency_id = agency.id
left join ad on ad.agent_id = agent.id
group by agency.agency_name

Upvotes: 1

juergen d
juergen d

Reputation: 204924

Since you did not provide the exact table structure I have to guess a little

select agency.agency_name, 
       count(ad.id) as ad_count
from agency 
left outer join agent on agency.id = agent.agency_id
left outer join ad on ad.id = agent.ad_id
group by agency.agency_name

Upvotes: 1

Related Questions