Something like SELECT DISTINCT ON, but for N > 1

非 Y 不嫁゛ 提交于 2020-05-17 06:26:12

问题


If I want to get the first row, or the most recent single row on a field in postgres, select distinct on seems great, see this answer.

DISTINCT ON is a syntax for wanting exactly 1 entry. But what if I want the N most recent entries? How would I transform this:

CREATE VIEW your_view AS
SELECT DISTINCT ON (id) *
FROM your_table a
ORDER BY id, date DESC;

But for

"Select the most recent n=2 entries per id" rather than "select the most recent n=1 entries per id?" ?

I assume it's an group by subquery, but I'm not quite seeing it.


回答1:


For a greatest-n-per-group query with n > 1 you typically use a window function:

select *
from (
  select *, row_number() over (partition by id order by "date" desc" as rn
  from the_table
) x
where rn <= 2;


来源:https://stackoverflow.com/questions/61570170/something-like-select-distinct-on-but-for-n-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!