gpt4 book ai didi

SQL:Last_Value() 返回错误结果(但 First_Value() 工作正常)

转载 作者:行者123 更新时间:2023-12-02 08:59:26 30 4
gpt4 key购买 nike

我在 SQL Server 2012 中有一个表,如快照所示:

enter image description here

然后我使用 Last_Value() 和 First Value 来获取不同 YearMonth 的每个 EmpID 的 AverageAmount。脚本如下:

SELECT A.EmpID,  
First_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey asc) AS '200901AvgAmount',
Last_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey asc) AS '201112AvgAmount'

FROM Emp_Amt AS A

但是,此查询的结果是:

result

在“201112AvgAmount”列中,每个 EmpID 显示不同的值,而“200901AvgAmount”具有正确的值。

我的 SQL 脚本有什么问题吗?我在网上做了很多研究,但仍然找不到答案......

最佳答案

这里有一个快速查询来说明该行为:

select 
v,

-- FIRST_VALUE() and LAST_VALUE()
first_value(v) over(order by v) f1,
first_value(v) over(order by v rows between unbounded preceding and current row) f2,
first_value(v) over(order by v rows between unbounded preceding and unbounded following) f3,
last_value (v) over(order by v) l1,
last_value (v) over(order by v rows between unbounded preceding and current row) l2,
last_value (v) over(order by v rows between unbounded preceding and unbounded following) l3,

-- For completeness' sake, let's also compare the above with MAX()
max (v) over() m1,
max (v) over(order by v) m2,
max (v) over(order by v rows between unbounded preceding and current row) m3,
max (v) over(order by v rows between unbounded preceding and unbounded following) m4
from (values(1),(2),(3),(4)) t(v)

可以在此处查看上述查询的输出 ( SQLFiddle here ):

| V | F1 | F2 | F3 | L1 | L2 | L3 | M1 | M2 | M3 | M4 |
|---|----|----|----|----|----|----|----|----|----|----|
| 1 | 1 | 1 | 1 | 1 | 1 | 4 | 4 | 1 | 1 | 4 |
| 2 | 1 | 1 | 1 | 2 | 2 | 4 | 4 | 2 | 2 | 4 |
| 3 | 1 | 1 | 1 | 3 | 3 | 4 | 4 | 3 | 3 | 4 |
| 4 | 1 | 1 | 1 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |

很少有人想到应用于采用 ORDER BY 子句的窗口函数的隐式框架。在这种情况下,窗口默认为RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW框架。 (RANGE 与 ROWS 并不完全相同,但那是另一个故事了)。这样想一下:

  • v = 1 的行上,有序窗口的框架跨越 v IN (1)
  • v = 2 的行上,有序窗口的框架跨越 v IN (1, 2)
  • v = 3 行上,有序窗口的框架跨度 v IN (1, 2, 3)
  • v = 4 行上,有序窗口的框架跨度 v IN (1, 2, 3, 4)

如果您想防止这种行为,您有两种选择:

  • 有序窗口函数使用显式ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING子句
  • 在那些允许省略的窗口函数中不要使用 ORDER BY 子句(如 MAX(v) OVER())

更多详细信息请参见 this article about LEAD(), LAG(), FIRST_VALUE() and LAST_VALUE()

关于SQL:Last_Value() 返回错误结果(但 First_Value() 工作正常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15388892/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com