如何在 where 子句中使用 row_number
How to use row_number in a where clause
我正在尝试使用 window 函数获取最近的 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 子句中的语法,对吗?这是什么?
您需要派生 table:
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;
这基本上是语法糖,不会导致性能开销。
我正在尝试使用 window 函数获取最近的 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 子句中的语法,对吗?这是什么?
您需要派生 table:
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;
这基本上是语法糖,不会导致性能开销。