SQL 窗口函数 - NTH_VALUE - 如果我们对前 n-1 行使用 Order by,为什么会返回 NULL
所以,我正在谈论 SQL
Now 中的 NTH_VALUE(column,n) 我观察到的是,如果我使用 order by 子句并指定与 nth_value 中相同的列,则第一个所选列中的 n-1 行始终为 NULL。这是为什么?如果我想选择第三列,并且第三列存在,那么无论我是否使用 order by(同一列)子句,它都应该返回行号 1 和行号 2 的第三列? 另外,有什么办法可以解决它吗?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为 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.