PostgresQL窗口函数 last_value未返回预期结果原因排查

这是一篇个人学习笔记,仅供参考。
窗口函数(window function),或开窗函数,主要有以下几个:
row_number():无重复排序
rank():并列跳排,数字不连续
desc_rank():并列不跳排,数字连续
first_value():取回第一行的值
last_value():取回最后一行的值
nth_value():取回第N行的值

一般的聚合函数(aggregate function)如sum、avg等加上over()关键字也可以转化为窗口函数,不是本文重点。本文主要讲以last_value()为代表的后三个函数。
由于本人在实际使用中发现last_value()函数没有正确返回想要的结果,故上网查询,记录如下。

官网文档提到:
Note that first_value, last_value, and nth_value consider only the rows within the “window frame”, which by default contains the rows from the start of the partition through the last peer of the current row. This is likely to give unhelpful results for last_value and sometimes also nth_value. You can redefine the frame by adding a suitable frame specification (RANGE, ROWS or GROUPS) to the OVER clause. See Section 4.2.8 for more information about frame specifications.
明确指出不正确的使用可能导致last_value和nth_value返回与预期不符的结果。需要在over从句中加上{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]

举例:查找每个班级的最低分
select class, name, score, last_value(score) over(partition by class order by score RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
from test_table
想知道更详细的使用说明,请参考如下两个官方文档。

参考:

  1. https://www.postgresql.org/docs/14/functions-window.html#FUNCTIONS-WINDOW-TABLE
  2. https://www.postgresql.org/docs/14/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值