zoukankan      html  css  js  c++  java
  • 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排序;


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

  • 相关阅读:
    用Visual C#创建Windows服务程序
    C# WinForm窗口最小化到系统托盘
    C# ?? 运算符是什么?
    linux中守护进程启停工具start-stop-daemon
    linux shell脚本中 mode=${1:-sart} filename=${fileuser:-"filename"}
    Unix/Linux 脚本中 “set -e” 的作用
    利用Sonar定制自定义扫描规则
    docker 镜像详解
    Docker Compose使用
    docker搭建gitlab、Redmine
  • 原文地址:https://www.cnblogs.com/telwanggs/p/14485594.html
Copyright © 2011-2022 走看看