如何按每个组的最高值对组进行排序 [英] How do I order groups by each group's highest value

查看:80
本文介绍了如何按每个组的最高值对组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据:

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  

正在尝试:按分数 desc 从表顺序中选择 *,url asc 不起作用.它给出(没有明显变化):

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

推荐答案

您可以使用窗口函数 - 如果您运行的是 MySQL 8.0:

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

这篇关于如何按每个组的最高值对组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆