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 需要用它进行条件判定。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM