简体   繁体   English

如何选择每个组中具有最大值的第一行?

[英]How to select the first row which has the max value in each group?

I know how to select the max value of each group. 我知道如何选择每个组的最大值。 But when there are multiple rows with the same value, I only want to select the first one, how can I do that? 但是,当有多个具有相同值的行时,我只想选择第一行,该怎么办?

For example, the table is something like: 例如,该表如下所示:

Group  Name  Value
A A1 20
A A2 20
A A3 10
B B1 20
B B2 30
B B3 30
B B4 10

The result I want is 我想要的结果是

A A1 20
B B2 30

There is no such thing as "the first row", because SQL tables represent unordered sets. 没有“第一行”之类的东西,因为SQL表表示无序集。 So, you need a column to specify what "first" is. 因此,您需要一列来指定“第一”是什么。

You can easily get one row. 你可以很容易地得到排。 One method is a correlated subquery: 一种方法是相关子查询:

select t.*
from t
where (name, value) = (select name, value
                       from t t2
                       where t2.group = t.group
                       order by t2.value desc
                       limit 1
                      );

In MySQL 8+, the canonical way would use row_number() : 在MySQL 8+中,规范的方式将使用row_number()

select t.*
from (select t.*, row_number() over (partition by group order by value desc) as seqnum
      from t
     ) t
where seqnum = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM