Understanding the LAST_VALUE() behaviour - SQL Server 2019

pmscorca 987 Reputation points
2021-10-15T15:22:40.717+00:00

Hi,
I'm trying to use the LAST_VALUE() OVER(...) function but I cannot understand a strange behaviour.
For this query I've obtained an unexpected result:

SELECT *,  
	LAST_VALUE(VALUE) OVER(PARTITION BY [YEAR] ORDER BY [YEAR]) as LAST_VALUE  
FROM Tab  
ORDER BY [DATE]  

140917-image.png

I'm waiting for the 14 value.

As the last row I've inserted the 2021-05-25 date.

/****** Object:  Table [dbo].[Tab]    Script Date: 15/10/2021 17:21:18 ******/  
SET ANSI_NULLS ON  
GO  
  
SET QUOTED_IDENTIFIER ON  
GO  
  
CREATE TABLE [dbo].[Tab](  
	[YEAR] [smallint] NULL,  
	[DATE] [date] NULL,  
	[VALUE] [int] NULL  
) ON [PRIMARY]  
GO  
  
  

Now, any helps to me, please? Many thanks

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,624 questions
{count} votes

11 answers

Sort by: Most helpful
  1. Dominic Tripodi 0 Reputation points
    2023-02-16T17:36:54.2933333+00:00

    Hey All, I can't find a good explanation of this either, and I feel like no one is really understanding the OPs question. "Why does the field in the ORDER BY clause get applied to the partition when we don't include RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"

    I am also trying to understand why this is happening.

    If we remove the ORDER BY it almost works as expected, because the PARTITION creates the range for the window function, but then if the result set is in a different order, the "last" value will be different because the order is different.

    In other window functions the ORDER BY clause does not affect the range of the window. If we compare FIRST_VALUE as an example, we can see that it works as expected without adding "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"

    User's image

    Does anyone know why LAST_VALUE includes the ORDER BY in the partition, or what is actually happening if it is not including ORDER BY in the partition?

    Thanks,
    Dominic

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.