【问题标题】:How can I select rows corresponding to the unique pair of column values with the highest value of another column in PostgreSQL?如何选择与 PostgreSQL 中另一列的最高值的唯一列值对对应的行?
【发布时间】:2021-04-11 03:22:16
【问题描述】:

我的桌子是这样的:

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

我需要为每个唯一的 A、B 对选择 X 列中值最高的行。

结果将是:

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

【问题讨论】:

    标签: sql postgresql group-by greatest-n-per-group


    【解决方案1】:

    我会推荐distinct on

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

    这允许您从行中选择除abx 之外的其他列。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        这样会起作用:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-17
          • 2018-08-25
          • 1970-01-01
          • 1970-01-01
          • 2018-06-22
          相关资源
          最近更新 更多