简体   繁体   中英

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. 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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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