【问题标题】:Select row in group with largest value in particular column postgres在特定列 postgres 中选择具有最大值的组中的行
【发布时间】:2021-01-26 23:49:36
【问题描述】:

我有一个如下所示的数据库表。

 id       account_id      action             time_point

 3        234            delete                100
 1        656            create                600
 1        4435           update                900
 3        645            create                50

我需要按 id 对该表进行分组,并选择 time_point 具有最大值的特定行。

结果表应如下所示:

 id       account_id      action             time_point

 3        234            delete                100
 1        4435           update                900

感谢您的帮助, qwew

【问题讨论】:

    标签: sql postgresql sql-order-by greatest-n-per-group window-functions


    【解决方案1】:

    在 Postgres 中,我会推荐 distinct on 来解决这个前 1 个每组问题:

    select distinct on (id) *
    from mytable
    order by id, time_point desc
    

    但是,这不允许绑定。如果是这样,rank() 是更好的解决方案:

    select *
    from (
        select t.*, rank() over(partition by id order by time_point desc) rn
        from mytable t
    ) t
    where rn = 1
    

    或者,如果您正在运行 Postgres 13:

    select *
    from mytable t
    order by rank() over(partition by id order by time_point desc)
    fetch first row with ties
    

    【讨论】:

      【解决方案2】:

      检查一下。

      select * from x
      where exists (
        select 1 from x xin
        where xin.id = x.id 
        having max(time_point) = time_point
      );
      

      【讨论】:

        猜你喜欢
        • 2021-07-23
        • 2023-04-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 2019-06-25
        • 1970-01-01
        相关资源
        最近更新 更多