类似于 SELECT DISTINCT ON,但对于 N > 1

Something like SELECT DISTINCT ON, but for N > 1

如果我想在 postgres 中获取第一行或字段中的最新单行,select distinct on 看起来不错,see this answer

DISTINCT ON 是一种只需要 1 个条目的语法。但是如果我想要 N 个最近的条目怎么办?我将如何转换它:

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

但是

"Select the most recent n=2 entries per id" 而不是 "select the most recent n=1 entries per id?" ?

我假设它是按子查询分组,但我不太明白。

对于 n > 1 的 查询,您通常使用 window 函数:

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