简体   繁体   中英

How can I select rows corresponding to the unique pair of column values with the highest value of another column in PostgreSQL?

My table looks like this:

A B X
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
2 2 1
2 2 2
2 2 3

I need to select the row with the highest value in X column for each unique A, B pair.

The result would be:

A B X
1 1 3
1 2 2
2 2 3

You can use the MAX aggregate function as follows:

select A, B, MAX(X) AS X
  from YOUR_TABLE
group by A, B

I would recommend distinct on :

select distinct on (a, b) t.*
from t
order by a, b, x desc;

This allows you to select other columns from the rows, other than a , b , and x .

With an index on (a, b, x desc) , this would typically be the fastest solution.

That would work like that:

select * from a where x = (select max(x) from a)

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