Skip to main content
Version: V1.0.0

NTH_VALUE

Syntax

NTH_VALUE (measure_expr, n) [ FROM { FIRST | LAST } ] [ { RESPECT | IGNORE } NULLS ] OVER (analytic_clause)

Description

The NTH_VALUE function returns the value of the expr expression at the nth position, with the direction specified by [ FROM { FIRST | LAST } ], which defaults to FROM FIRST. It also includes a flag to indicate whether to ignore NULL values. The window is defined by the analytic_clause.

In this function, n must be a positive integer. If n is NULL, the function returns an error. If n exceeds the number of rows in the window, the function returns NULL.

Examples

CREATE TABLE EXPLOYEES(LAST_NAME CHAR(10), SALARY DECIMAL, JOB_ID CHAR(32));
Query OK, 0 rows affected (0.036 sec)

INSERT INTO EXPLOYEES VALUES('JIM', 2000, 'CLEANER');
Query OK, 1 row affected (0.001 sec)

INSERT INTO EXPLOYEES VALUES('MIKE', 12000, 'ENGINEERING');
Query OK, 1 row affected (0.001 sec)

INSERT INTO EXPLOYEES VALUES('LILY', 13000, 'ENGINEERING');
Query OK, 1 row affected (0.001 sec)

INSERT INTO EXPLOYEES VALUES('TOM', 11000, 'ENGINEERING');
Query OK, 1 row affected (00.001 sec)

SELECT LAST_NAME, FIRST_VALUE(SALARY) OVER(PARTITION BY JOB_ID) FIRST_S, LAST_VALUE(SALARY) OVER(PARTITION BY JOB_ID) LAST_S, NTH_VALUE(SALARY,2) OVER(PARTITION BY JOB_ID) 2ND_S FROM EXPLOYEES;
+-----------+---------+--------+-------+
| LAST_NAME | FIRST_S | LAST_S | 2ND_S |
+-----------+---------+--------+-------+
| JIM | 2000 | 2000 | NULL |
| MIKE | 12000 | 11000 | 13000 |
| LILY | 12000 | 11000 | 13000 |
| TOM | 12000 | 11000 | 13000 |
+-----------+---------+--------+-------+
4 rows in set (0.003 sec)