Question on Window Function 2

Mikhail Firsov 1,876 Reputation points
2021-03-19T11:17:15.53+00:00

Hello,

Help me please with this:

79550-q-fv-lv.png

Thank you in advance,
Michael

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

Accepted answer
  1. Erland Sommarskog 100.8K Reputation points MVP
    2021-03-19T23:20:15.917+00:00

    Yes, you get the last value so far when you only say ORDER BY col. When you leave out the window, this defaults to ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

    Try this for a variation:

    SELECT name, column_id, last_value(name) OVER(ORDER BY column_id ROWS BETWEEN 3 PRECEDING AND 2 FOLLOWING )
    FROM   sys.all_columns
    WHERE  object_id = object_id('sys.objects')
    

    `

    1 person found this answer helpful.

6 additional answers

Sort by: Most helpful
  1. Alberto Poblacion 1,551 Reputation points
    2021-03-19T11:25:42.577+00:00

    What is the type of the field "Quantity"? If it is not numeric, but rather varchar or nvarchar, then the result of ORDER BY Quantity will be that the largest value is 50 (not 200) because it will be ordered alphabetically. In this case, your LAST_VALUE will be the one associated to Quantity 50, which happens to be iPhone.

    0 comments No comments

  2. Viorel 111.8K Reputation points
    2021-03-19T11:28:01.453+00:00

    I think that the last value of this ordered set is ambiguous because there are three last values: Samsung (200), iPhone (200) and Samsung (200). Maybe other queries will return Samsung instead of iPhone and iPhone instead of Samsung, but it is not certain. Probably you can assume that the server takes one of values arbitrarily.

    0 comments No comments

  3. Mikhail Firsov 1,876 Reputation points
    2021-03-19T11:33:36.467+00:00

    Thank you all for your replies!

    "What is the type of the field "Quantity"?" - INT

    "I think that the last value of this ordered set is ambiguous because there are three last values: Samsung (200), iPhone (200) and Samsung (200)." - I thought of it but it's my understanding that if it was the iPhone chosen as the last value the iPhone should have been returned in ALL rows - NOT only from 1 to 7!


  4. Mikhail Firsov 1,876 Reputation points
    2021-03-19T13:46:53.927+00:00

    I've already tried to get rid of ties before posting:
    79649-q-fv-lv2.png

    "Maybe the experiments show that your understanding is incorrect.”." - I don't know how else I can interpret the wording "Returns the last value in an ordered set of values in SQL Server 2012."

    79686-q-fv-lv3.png