如何在WHERE子句中使用ROW_NUMBER [英] How to use row_number in a where clause

查看:0
本文介绍了如何在WHERE子句中使用ROW_NUMBER的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用窗口函数获取最新的n条记录,如下from here

我有:

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子句中的语法,对吗?这是什么?

推荐答案

您需要派生表:

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;

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

这篇关于如何在WHERE子句中使用ROW_NUMBER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆