Teradata SQL - LEAD and LAG OLAP Functions

access_time 11 months ago visibility545 comment 0

From Teradata 16, LEAD and LAG OLAP functions are supported. The LAG function returns data from a row preceding the current row at a specified offset in a window group; the LEAD function accesses data from a row following the current row at a specified offset in a window group.

Scenario

Table TD_MS_SAMPLE_DB.Employee has the following data. Find the EmployeeID for each employee that has closest salary to them.

Code snippet

select	EmployeeID,EmployeeName,Salary,
LAG(EmployeeID) ignore nulls over (
partition by 1
order by Salary) as EmployeeID_Lag,
LAG(Salary) ignore nulls over (
partition by 1
order by Salary) as Salary_Lag,
LEAD(EmployeeID) ignore nulls over (
partition by 1
order by Salary) as EmployeeID_Lead,
LEAD(Salary) ignore nulls over (
partition by 1
order by Salary) as Salary_Lead
from	TD_MS_SAMPLE_DB.Employee;

Sample output


copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

Follow Kontext

Get our latest updates on LinkedIn or Twitter.

Want to publish your article on Kontext?

Learn more

More from Kontext

visibility 252
thumb_up 0
access_time 5 months ago

In article  Teradata FastLoad - Load CSV File , it shows how to load CSV into Teradata. The input file is very basic CSV file.  This article expands on that to provide examples about loading CSV files with optional quoted fields to skip delimiters. It also shows how to load files with ...

visibility 786
thumb_up 0
access_time 5 months ago

This page shows how to create Hive tables with storage file format as CSV or TSV via Hive SQL (HQL). Example: CREATE TABLE IF NOT EXISTS hql.customer_csv(cust_id INT, name STRING, created_date DATE) COMMENT 'A table to store customer records.' ROW FORMAT SERDE ...

visibility 89
thumb_up 0
access_time 4 months ago

A procedure contains a number of SQL statements that will be executed in sequence in Teradata. Procedures can be used to return result sets to the invoking clients. In many other databases, it is very easy to return set records to the client in a procedure as SELECT statement can be directly used.