Updated on 2026-11-06 GMT+08:00

last_value

Function

The last_value function is used to retrieve the value of the last row in the window corresponding to the current row.

Usage Restrictions

The usage restrictions for window functions are as follows:

  • Window functions can only appear in SELECT statements.
  • Window functions cannot be nested with other window functions or aggregate functions.
  • Window functions cannot be used together with aggregate functions at the same level.

Syntax

last_value(<expr>[, <ignore_nulls>]) over ([partition_clause] [orderby_clause] [frame_clause])

Parameters

Parameter

Mandatory

Description

expr

Yes

The expression for which the result is to be computed and returned.

ignore_nulls

No

BOOLEAN type, specifies whether to ignore NULL values. The default value is False. When the parameter value is True, the last non-NULL value in the window is returned.

partition_clause

No

Specifies the partition. Rows with the same value in the partition column are considered to be within the same window.

orderby_clause

No

Specifies how data is sorted within a window.

frame_clause

No

Used to determine the data boundaries.

Return Values

The data type of the parameter.

Examples

To facilitate understanding of the function's usage, source data is provided along with function-related examples. Create the logs table and add data with the following example command:

create table logs(
  cookieid string,
  createtime string,
  url string 
)  
STORED AS parquet; 

Add data as follows:

cookie1 2015-04-10 10:00:02 url2 
cookie1 2015-04-10 10:00:00 url1 
cookie1 2015-04-10 10:03:04 url3 
cookie1 2015-04-10 10:50:05 url6 
cookie1 2015-04-10 11:00:00 url7 
cookie1 2015-04-10 10:10:00 url4 
cookie1 2015-04-10 10:50:01 url5 
cookie2 2015-04-10 10:00:02 url22 
cookie2 2015-04-10 10:00:00 url11 
cookie2 2015-04-10 10:03:04 url33 
cookie2 2015-04-10 10:50:05 url66 
cookie2 2015-04-10 11:00:00 url77 
cookie2 2015-04-10 10:10:00 url44 
cookie2 2015-04-10 10:50:01 url55 

Example: Group all records by cookieid, sort by createtime in ascending order, and return the last row of data in each group. Example command:

SELECT cookieid, createtime, url,
        LAST_VALUE(url) OVER(PARTITION BY cookieid ORDER BY createtime) AS last 
FROM logs;  
-- Result:
cookieid createtime         url last 
cookie1 2015-04-10 10:00:00 url1 url1 
cookie1 2015-04-10 10:00:02 url2 url2 
cookie1 2015-04-10 10:03:04 url3 url3 
cookie1 2015-04-10 10:10:00 url4 url4 
cookie1 2015-04-10 10:50:01 url5 url5 
cookie1 2015-04-10 10:50:05 url6 url6 
cookie1 2015-04-10 11:00:00 url7 url7 
cookie2 2015-04-10 10:00:00 url11 url11 
cookie2 2015-04-10 10:00:02 url22 url22 
cookie2 2015-04-10 10:03:04 url33 url33 
cookie2 2015-04-10 10:10:00 url44 url44 
cookie2 2015-04-10 10:50:01 url55 url55 
cookie2 2015-04-10 10:50:05 url66 url66 
cookie2 2015-04-10 11:00:00 url77 url77 

Note: The last value up to the current row is essentially the current row itself.