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