简体   繁体   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?

My table looks like this:我的表如下所示:

A一个 B X X
1 1 1 1 1 1
1 1 1 1 2 2
1 1 1 1 3 3
1 1 2 2 1 1
1 1 2 2 2 2
2 2 2 2 1 1
2 2 2 2 2 2
2 2 2 2 3 3

I need to select the row with the highest value in X column for each unique A, B pair.对于每个唯一的 A、B 对,我需要 select X 列中具有最高值的行。

The result would be:结果将是:

A一个 B X X
1 1 1 1 3 3
1 1 2 2 2 2
2 2 2 2 3 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 行中的其他列,而不是abx

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.

相关问题 在标准SQL中,如何选择行,以便对于一列中的每个唯一值,另一列中的所有值都是指定值? - 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? 选择在指定列中具有最高值的行,而在其他列中不具有唯一值的行应该是不同的 - Select rows with highest value in a specified column and not unique values in other column should be distinct Select 行使用 group by 并且在每个组中获取基于另一个列值的最高值的列值 - Select rows using group by and in each group get column values based on highest of another column value 如何 select 特定列具有最高值而另一列具有特定值的行 - How to select rows where a specific column has the highest value and another column has a specific value 根据另一列中的最高值从列中选择不同的值 - Select distinct values from a column based on highest value in another column 如何选择唯一的列值并显示其另一列的值的总和? - How do I select a unique column value and display its sum of values of another column? 如何从另一列的最高不同值中选择一个列值 - How to select a column value from the highest distinct value of another column 在 PostgreSQL 中,根据另一列的最小值返回具有唯一值的行 - In PostgreSQL, return rows with unique values of one column based on the minimum value of another 当另一列在oracle中具有不同的值时,如何选择MAX(列)行? - How can I select rows with MAX(Column) when another column has distinct values in oracle? 如何选择N个具有唯一列值的最新行 - How can I Select N most recent rows with unique column values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM