为什么 T-SQL 中的 LAG 函数是不确定的?

Why the LAG function in T-SQL is non-deterministic?

我正在尝试在 T-SQL 中使用 LAG 来计算一些滞后特征。当 LAG reference page says that this function is non-deterministic. The reference page on function determinism 说 "specifying an ORDER BY clause in a query does not change the determinism of a function that used in that query" 时,我有点担心。但是,我不明白为什么 LAG 在相同条件下会 return 不同的结果。如果是这样,人们为什么要使用它?也许我没有正确解释 "determinism"?谢谢!

In mathematics and physics, a deterministic system is a system in which no randomness is involved in the development of future states of the system. A deterministic model will thus always produce the same output from a given starting condition or initial state. https://en.wikipedia.org/wiki/Deterministic_system

LAG 函数本身不是确定性的,因为它的结果会根据数据状态而改变,Eric 是正确的。在某些数据模型中,如果应用正确,它可以是确定性的(比如如果您在滞后时按数字键排序)但函数定义本身不是确定性的。

有道理吗?

根据 MSDN documentation,非确定性函数每次使用一组特定的输入值调用时可能会 return 不同的结果,即使它们访问的数据库状态保持不变,也是如此,因此这与数据更改无关(INSERT, DELETE, UPDATE).

但是,Eric 对物理排序顺序的看法是正确的。物理排序顺序可能因一个查询而异,例如,当数据中存在重复行时。在那种情况下,LAGLEAD 可以 return 不同的结果,具体取决于所选的执行计划。另一方面,AVG 函数是确定性的,因为对于相同的数据集,无论排序顺序如何,它总是 return 相同的结果。