Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by count with postgresql?

I have two tables:

Companies: (id, name, city) Workers: (id, name) 

I would like to get all companies and sort them by numbers of employes.

The result should give:

count | company id | company name | city ------------------------------------------ 90         6           foo corp      NY 45         9           bar corp      LA 0          3         foobar corp     HO 

I tried:

select      c.*,      count(w.id) as c  from      companies c  left join      workers w  on      c.id = w.company_id  group by      c.id  order by      c desc; 

But that's not working as it tells me to group by g.name too :/

Any ideas?

like image 754
Ggolo Avatar asked Sep 09 '09 23:09

Ggolo


People also ask

How do I sort by count in SQL?

Use ORDER BY with DESC to order in descending order. For counting the values, use the COUNT(). For example, if the name “John” appears thrice in the column, then a separate column will display the count 3 and in this way all the count values will be arranged in descending order using the ORDER BY DESC.

Can we use count in ORDER BY?

For uninitiated, a COUNT() function is used to find the total number of records in the result set. It is usually used in combination with the GROUP BY clause to prepare a summary of the total number of records in each group. It can further be used with ORDER BY clause to sort the obtained summary table.


1 Answers

You've aliased the table and column as the same thing, so don't do that. It's not invalid, just tough to follow.

Anyway, include all columns that you're selecting that aren't aggregates in your group by:

select      count(w.id) as mycount,     w.company_id,     c.company_name,     c.city from      companies c      left join workers w on          c.id=w.company_id  group by      w.company_id,     c.company_name,     c.city order by mycount desc; 
like image 133
Eric Avatar answered Sep 30 '22 18:09

Eric