【问题标题】:How to use row_number in a where clause如何在 where 子句中使用 row_number
【发布时间】:2020-05-03 06:56:27
【问题描述】:

我正在尝试使用窗口函数来获取最近的 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 子句中的语法,对吗?这是什么?

【问题讨论】:

    标签: postgresql subquery greatest-n-per-group column-alias


    【解决方案1】:

    你需要一个派生表:

    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 子句在内部选择与外部选择中是否存在性能差异?
    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 2013-10-08
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 2020-11-30
    相关资源
    最近更新 更多