0

我正在尝试使用窗口函数来获取最近的 n 记录,从这里开始

我有:

select 
   id,
   blah,
   row_number () over (
     partition by blah, my_id
     order by datetime) rn,
   theme
from documents
where theme = 'cats';

我得到:

 id | blah | rn | theme 
----+-----+----+-------
  1 |   1 |  1 | cats
  2 |   1 |  2 | cats
  3 |   1 |  3 | cats
  4 |   1 |  4 | cats
  5 |   1 |  5 | cats
  9 |   2 |  1 | cats
  8 |   2 |  2 | cats
 11 |   3 |  1 | cats
 12 |   4 |  1 | cats
 13 |   5 |  1 | cats
 14 |   6 |  1 | cats
(11 rows)

这是伟大的。但我想要不超过 2 行,rn <= 2例如。我想象这类似于:

select 
   id,
   blah,
   row_number () over (
     partition by blah, my_id
     order by datetime) rn,
   theme
from documents
where theme = 'cats' and
rn <= 2;

但我得到:

ERROR:  column "rn" does not exist
LINE 15: rn <= 1;
         ^

我知道我可以像链接问题一样将其设为子查询,但是我必须缺少将 row_number 放在 where 子句中的语法,对吗?它是什么?

4

1 回答 1

2

您需要一个派生表:

select id, blah, them
from (
  select id,
         blah,
         row_number () over (partition by blah, my_id order by datetime) rn,
         theme
  from documents
) x
where theme = 'cats' 
and rn <= 2;

这基本上是语法糖,不会导致性能开销。

于 2020-05-03T07:24:27.450 回答