6

我有一个t包含以下数据的表:

    name    | n
------------+---
 school     | 4
 hotel      | 2
 restaurant | 6
 school     | 3
 school     | 5
 hotel      | 1

当我运行以下查询时,结果有些奇怪。

select name, n,
       first_value(n) over (partition by name order by n desc),
       last_value(n) over (partition by name order by  n)
from t;

    name    | n | first_value | last_value
------------+---+-------------+------------
 hotel      | 1 |           2 |          1
 hotel      | 2 |           2 |          2
 restaurant | 6 |           6 |          6
 school     | 3 |           5 |          3
 school     | 4 |           5 |          4
 school     | 5 |           5 |          5
(6 rows)

虽然first_value按我的预期工作,但last_value工作很奇怪。我认为last_valuecolumn 的值应该与first_value's 相同,因为它first_value是按n降序排列的。

这是 PostgreSQL 的错误还是我错过了什么?

PostgreSQL 的版本是:

postgres=# select version();
                                                              version
-----------------------------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.4.1 on x86_64-apple-darwin14.1.0, compiled by Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn), 64-bit
(1 row)
4

1 回答 1

11

不,这不是错误。first_value()andlast_value()函数作用于窗框,而不是分区。根据文档frame_clause,如果未指定,则窗口框架默认为当前行的分区开始。这正是您所需要的,first_value()last_value()您应该添加range between unbounded preceding and unbounded following到您的WINDOW定义中以超越当前行:

select name, n,
       first_value(n) over (partition by name order by n desc),
       last_value(n) over (partition by name order by n
         range between unbounded preceding and unbounded following)
from t;

另请注意,这与分区中行的顺序无关。排序以特定顺序生成分区(毫不奇怪),然后基于框架的函数在窗口框架上工作,而不知道或关心行的任何排序。

于 2015-05-07T04:50:26.413 回答