使用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 需要用它進行條件判定。