![](/img/trans.png)
[英]In standard SQL, how do I select rows such that for each unique value in one column, all of the values in another column are a specified value?
[英]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 |
结果将是:
一个 | 乙 | 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 行中的其他列,而不是a
、 b
和x
。
使用(a, b, x desc)
上的索引,这通常是最快的解决方案。
那会这样工作:
select * from a where x = (select max(x) from a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.