LAST_VALUE function [Aggregate]

Function

Returns the last value from a set of values.

Syntax

LAST_VALUE (expression [IGNORE NULLS | RESPECT NULLS])
OVER (window-spec)

Parameters

expression The expression on which to determine the last value in an ordered set.

Usage

LAST_VALUE returns the last value in a set of values, which is usually an ordered set. If the last value in the set is null, then the function returns NULL unless you specify IGNORE NULLS. If you specify IGNORE NULLS, then LAST_VALUE returns the last non-null value in the set, or NULL if all values are null.

The data type of the returned value is the same as that of the input value.

You cannot use LAST_VALUE or any other analytic function for expression. That is, you cannot nest analytic functions, but you can use other built-in function expressions for expression.

If the window-spec does not contain an ORDER BY then the result is arbitrary. If there is no window-spec, then the result is arbitrary.

You can specify elements of window-spec either in the function syntax (inline), or with a WINDOW clause in the SELECT statement. For information on how to specify the window, see “Analytical functions”.

NoteDISTINCT is not supported.

Example

The following example returns the salary of each employee, plus the name of the employee with the highest salary in their department:

SELECT GivenName + ' ' + Surname AS employee_name, 
	Salary, DepartmentID,
	LAST_VALUE( employee_name ) OVER Salary_Window AS 	 highest_paid
FROM Employees
WINDOW Salary_Window AS ( PARTITION BY DepartmentID ORDER BY Salary 
	RANGE BETWEEN UNBOUNDED PRECEDING 
	AND UNBOUNDED FOLLOWING )
ORDER BY DepartmentID DESC;

The returned result set is:

Table 4-23:

employee_name

Salary

DepartmentID

highest_paid

Michael Lynch

24903.000

500

Jose Martinez

Joseph Barker

27290.000

500

Jose Martinez

Sheila Romero

27500.000

500

Jose Martinez

Felicia Kuo

28200.000

500

Jose Martinez

Jeannette Bertrand

29800.000

500

Jose Martinez

Jane Braun

34300.000

500

Jose Martinez

Anthony Rebeiro

34576.000

500

Jose Martinez

Charles Crowley

41700.000

500

Jose Martinez

Jose Martinez

55500.800

500

Jose Martinez

Doug Charlton

28300.000

400

Scott Evans

Elizabeth Lambert

29384.000

400

Scott Evans

Joyce Butterfield

34011.000

400

Scott Evans

Robert Nielsen

34889.000

400

Scott Evans

Alex Ahmed

34992.000

400

Scott Evans

Ruth Wetherby

35745.000

400

Scott Evans

...

...

...

...

Standards and compatibility