Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by COUNT per value

I have a table which stores IDs and the city where the store is located.

I want to list all the stores starting with the stores that are in the city where there are the most stores.

TABLE

ID CITY 1  NYC 2  BOS 3  BOS 4  NYC 5  NYC 

The output I want is the following since I have the most stores in NYC, I want all the NYC location to be listed first.

1  NYC 4  NYC 5  NYC 2  BOS 3  BOS 
like image 236
Enkay Avatar asked Feb 17 '10 18:02

Enkay


People also ask

How do I arrange a count in descending order in SQL?

The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you ORDER 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 I use ORDER BY with count?

ORDER BY COUNT clause in standard query language(SQL) is used to sort the result set produced by a SELECT query in an ascending or descending order based on values obtained from a COUNT function. For uninitiated, a COUNT() function is used to find the total number of records in the result set.


1 Answers

SELECT count(City), City FROM table GROUP BY City ORDER BY count(City); 

OR

SELECT count(City) as count, City FROM table GROUP BY City ORDER BY count; 

Ahh, sorry, I was misinterpreting your question. I believe Peter Langs answer was the correct one.

like image 132
MindStalker Avatar answered Sep 20 '22 06:09

MindStalker