badgers
badgers

Reputation: 23

MySQL Query Order By Most Occurrences

I have a MySQL table, setup like this:

id  |  game_type | votes  
01  |  aaa       |  2  
02  |  bbb       |  2  
03  |  ccc       |  4  
04  |  aaa       |  7  
05  |  aaa       |  1  
06  |  ccc       |  11  

I would like to return all the rows, so they are ordered by game_type, but with the most occurrences of game type in descending order, AND THEN ordered by the amount of voted in descending order, like this:

04 aaa  7  
01 aaa  2  
05 aaa  1  
06 ccc  11  
03 ccc  4  
02 bbb  2

If I just have the ORDER BY at the end of the query, it just groups them in a random order.

How could I achieve this?

Upvotes: 1

Views: 284

Answers (1)

Holger Brandt
Holger Brandt

Reputation: 4354

Try this:

SELECT M.id, M.game_type, M.votes 
FROM MyTable AS M INNER JOIN
    (SELECT game_type, COUNT(game_Type) AS TypeCount
     FROM MyTable
     GROUP BY game_type
     ORDER BY COUNT(game_Type) DESC) AS U
  ON M.game_type=U.game_type
ORDER BY U.TypeCount DESC, M.game_type, M.votes DESC

Upvotes: 1

Related Questions