SQL: Last_Value() returns wrong result (but First_Value() works fine)

后端 未结 3 1790
野的像风
野的像风 2020-12-08 08:36

I have a table in SQL Server 2012 as the snapshot shows:

\"enter

Then I\'m usi

3条回答
  •  忘掉有多难
    2020-12-08 09:19

    There is nothing wrong with your script, this is a way how partitioning works in SQL server :/. If you change LAST_VALUE to MAX result will be the same. Solution would be:

    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 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS '201112AvgAmount'  
    FROM  Emp_Amt  AS A
    

    There is a great post about it, link. GL!

提交回复
热议问题