• PostgreSQL提取每个ID的最后一行(Postgresql extract last row for each id)


    Suppose I've next data

      id    date          another_info
      1     2014-02-01         kjkj
      1     2014-03-11         ajskj
      1     2014-05-13         kgfd
      2     2014-02-01         SADA
      3     2014-02-01         sfdg
      3     2014-06-12         fdsA
    

    I want for each id extract last information:

      id    date          another_info
      1     2014-05-13         kgfd
      2     2014-02-01         SADA
      3     2014-06-12         fdsA
    

    How could I manage that?

    解决方案

    The most efficient way is to use Postgres' distinct on operator

    select distinct on (id) id, date, another_info
    from the_table
    order by id, date desc;
    

    If you want a solution that works across databases (but is less efficient) you can use a window function:

    select id, date, another_info
    from (
      select id, date, another_info, 
             row_number() over (partition by id order by date desc) as rn
      from the_table
    ) t
    where rn = 1
    order by id;
    

    The solution with a window function is in most cases faster than using a sub-query.

     

    假设我有下一个数据



      id date another_info 
    1 2014-02-01 kjkj
    1 2014-03-11 ajskj
    1 2014-05-13 kgfd
    2 2014-02-01 SADA
    3 2014-02-01 sfdg
    3 2014-06- 12 fdsA


    我想为每个id提取最新信息:



      id date another_info 
    1 2014-05-13 kgfd
    2 2014-02-01 SADA
    3 2014-06-12 fdsA


    我该如何处理?


    解决方案

    最有效的方法是在运算符上使用Postgres的 distinct



     从(_id)id,日期,the_table 
    的id,日期desc中选择另一个信息



    如果您想要一个跨数据库的解决方案(但效率较低),则可以使用窗口函数:



     选择ID,日期,another_info 
    from(
    选择ID,日期,another_info,
    row_number()结束(按日期desc按ID顺序划分),从the_table
    中为rn
    )t
    其中rn = 1
    ,按id排序;


    带有窗口功能的解决方案在大多数情况下比使用子查询要快。

  • 相关阅读:
    wget 命令用法详解
    VI编辑器的使用方法
    Android APK反编译就这么简单 详解(附图)
    Nginx与X-Sendfile
    腾讯微博OAuth2.0认证介绍
    haporoxy的keeplaive ZZ
    如何监听非本地IP
    haproxy配置直接重定向url
    LVS与其他负载均衡软件的区别
    J2EE基础总结(4)——JSP
  • 原文地址:https://www.cnblogs.com/telwanggs/p/14485594.html
Copyright © 2020-2023  润新知