SQL 窗口函数 - NTH_VALUE - 如果我们对前 n-1 行使用 Order by,为什么会返回 NULL

发布于 2025-01-13 09:31:50 字数 351 浏览 1 评论 0原文

输入图片这里的描述

所以,我正在谈论 SQL

Now 中的 NTH_VALUE(column,n) 我观察到的是,如果我使用 order by 子句并指定与 nth_value 中相同的列,则第一个所选列中的 n-1 行始终为 NULL。这是为什么?如果我想选择第三列,并且第三列存在,那么无论我是否使用 order by(同一列)子句,它都应该返回行号 1 和行号 2 的第三列? 另外,有什么办法可以解决它吗?

enter image description here

So, I am talking about the NTH_VALUE(column,n) in SQL

Now What I observed is that if I used to order by clause and specify the same column as inside nth_value, the first n-1 rows are always NULL in the selected column. Why is that? IF I want to select the 3rd column to say, and the 3rd column exists, it should return the 3rd column for row number 1 and 2 as well in spite of whether I use the order by(same column) clause or not?
ALso, any way to get around with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听你说爱我 2025-01-20 09:31:50

发生这种情况是因为 sql 使用的默认框架子句是无界前一行和当前行之间的范围。这意味着它只会考虑当前行之前的行来获取第 n 个值。因此,对于直到 N-1 的行,您将得到 NULL,因为第 N 个值超出了这 N-1 行。

解决方案:

如果您将其更改为 over() 内的无界前置和无界后置之间的范围,那么您将不会使用第 N 个值窗口函数获得 NULL 值。

This happens because the default frame clause that sql uses is range between unbounded preceding and current row. This means it will only consider rows till the current row to get the nth value. So for the rows till N-1, you'll get NULL because Nth value is beyond these N-1 rows.

Solution:

If you change that to range between unbounded preceding and unbounded following inside over() then you won't get NULL values with the Nth value window function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文