How do I order groups by each group's highest value

╄→гoц情女王★ 提交于 2021-02-05 12:14:19

问题


I have data:

query url score  
a www.google.com 3  
a www.facebook.com 2  
a www.google.com 1

I want to 'group' entries by their domain, and then order (desc) the domain groups by each group's highest score so I get:

query url score  
a www.google.com 3  
a www.google.com 1
a www.facebook.com 2  

Trying: select * from table order by score desc, url asc doesnt work. It gives (no apparent change):

query url score  
a www.google.com 3  
a www.facebook.com 2  
a www.google.com 1

回答1:


You can use window functions - if you are running MySQL 8.0:

select *
from mytable
order by max(score) over(partition by url) desc, score desc

In earlier versions, one option uses a subquery:

select *
from mytable t
order by 
    (select max(score) from mytable t1 where t1.url = t.url) desc,
    score desc


来源:https://stackoverflow.com/questions/63193038/how-do-i-order-groups-by-each-groups-highest-value

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