views:

204

answers:

2

I have two tables:

Companies: (id, name)

Workers: (id, name, country)

I would like to get all companies and sort them by numbers of employees from a given country.

For a query looking for companies that have more workers from the USA, the result should give:

#workers from USA | company id | company name 
----------------------------------------------
        90              6           foo corp     
        45              9           bar corp     
        0               3         foobar corp

I tried:

select 
    count(w.country='USA') as mycount,
    w.company_id,
    c.company_name
from 
    companies c 
    left join workers w on 
        c.id=w.company_id 
group by 
    w.company_id,
    c.company_name
order by mycount desc;

But that's counting all workers regardless of their countries.

Any ideas?

A: 

Does replacing COUNT(w.country='USA') with COUNT(*) help? I believe your query needs to refer to fields on the Companies table as opposed to workers because your left join leaves open the possibility that the set of workers pulled for a specific company/country is the empty set.

Try:

select count(*) as mycount,
       c.company_id,
       c.company_name
from   companies c
left join workers w on c.id=w.company_id 
group by c.company_id, c.company_name
order by mycount desc;
David Andres
@Ggolo: see my edit to this post.
David Andres
Actually I want my query to return even companies that have no workers from the US, in that case mycount should return 0.
Ggolo
replacing COUNT(w.country='USA') with COUNT(*) returns all workers, I want number to count the number of workers from USA only.
Ggolo
+3  A: 

You can do that easily with a correlated subquery:

SELECT
  (SELECT count(*) FROM workers w WHERE w.company_id=c.id AND w.country='USA') AS mycount,
  c.id,
  c.company_name
FROM
  companies c
ORDER BY mycount DESC
Magnus Hagander