postgre 获取分组中的一条数据,最大值或最小值等

使用postgre的窗口函数row_number, 分块后选择需要自己的行

例:获取分组中的最大数据,从table1表中获取以cloumn1字段作为分组,每组中cloum2字段最大的行数据

  

  select *

    from(

      select * ,row_number() over (partition by colum1 order by cloum2 desc nulls last)order_in_  clomun1 from table1

     )as temp

  where order_in_  clomun1< 2

  ↑解释如下:

    row_number():  在其分区中的当前行号,从1计(所以后面的where条件是<2,取出来的就是最大值), 文档地址 http://www.postgres.cn/docs/9.3/functions-window.html

    partition by colum1:  根据cloumn1进行分组,在这里不能使用order by    

    order_in_  clomun1:  分组集合的别名,随便命名,后面的 where 需要用它进行条件判定。

 

posted @ 2020-05-15 18:34  bl_plus_yan  阅读(4443)  评论(0)    收藏  举报