繁体   English   中英

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

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

我的表如下所示:

一个 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

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

结果将是:

一个 X
1 1 3
1 2 2
2 2 3

您可以使用MAX聚合 function 如下:

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

我会推荐distinct on

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

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

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

那会这样工作:

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

暂无
暂无

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

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