MySQL: “order by” inside of “group by”

假装没事ソ 提交于 2019-12-21 09:06:11

问题


I have a MySQL table of names, which consists of two fields: name and rank. The name value is not unique can have multiple matches.

The problem: I want to select records, grouped by name, but if there are more than one name, the one with the highest rank should be taken.

An example:

Tom 2

Ben 1

Ben 2

SELECT * FROM names GROUP BY name ORDER BY rank DESC

Usually returns:

Tom 2

Ben 1

I need:

Tom 2

Ben 2

Since there are two Bens, but the second one with a higher rank.

It seems, that MySQL grouping takes the first name and ignores the rest.

How do I order records inside "group by", so I could say which record should be taken, if there is more than one with the same name?


回答1:


You need an aggregate function called max:

select name, max(rank)
  from names
 group by name;

This way you will retrieve all distinct names, each one associated with its max rank.




回答2:


For me it has been worked:

To take the last row inside a group:

select * from 
( select name, rank from names order by rank desc ) as a 
group by name



回答3:


Use max():

select name,
       max(rank)
from names
group by name
order by max(rank) desc


来源:https://stackoverflow.com/questions/5362160/mysql-order-by-inside-of-group-by

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!