我怎样才能 select 与唯一的一对列值对应的行与 PostgreSQL 中另一列的最大值?

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

我的 table 看起来像这样:

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

我需要 select 每个唯一的 A、B 对在 X 列中具有最高值的行。

结果为:

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

您可以使用 MAX 聚合函数,如下所示:

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

这样就可以了:

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

我会推荐 distinct on:

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

这允许您 select 行中的其他列,而不是 abx

使用 (a, b, x desc) 上的索引,这通常是最快的解决方案。