[英]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 ![]() |
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:您可以使用
MAX
聚合 function 如下:
select A, B, MAX(X) AS X
from YOUR_TABLE
group by A, B
I would recommend distinct on
:我会推荐
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
.这允许您 select 行中的其他列,而不是
a
、 b
和x
。
With an index on (a, b, x desc)
, this would typically be the fastest solution.使用
(a, b, x desc)
上的索引,这通常是最快的解决方案。
That would work like that:那会这样工作:
select * from a where x = (select max(x) from a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.