SQL Server LEAD() function Overview
At many instances, user would really like to check the worth of the present row with the worth of the subsequent row. to resolve this problem in SQL Server’s LEAD() window function are often used.
Function provides access to a row at a set physical offset following this row. LEAD() function will allows to access data of the following row, or the row after the subsequent row, and continue on.
LEAD(return_value, offset [, default]) OVER ( [PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC] )
- return_value –
The return_value of the subsequent row supported a specified offset. The return_value must be one value.
- offset –
The offset is that the number of rows forward from the present row from where to access data. The offset should be a positive integer. If you don’t define the default value of offset is 1.
- default –
The LEAD() function results default if offset is beyond the scope of the partition. If not defined, default is NULL.
- PARTITION BY clause –
The PARTITION BY clause is optional, it differs rows of the result set into partitions to where the LEAD() function is used.
- ORDER BY clause –
The ORDER BY clause define logical order of the rows in each partition to where the LEAD() function is used.
Let us suppose we have below table named “CompanySales” :
Select * from CompanySales;
SELECT TOP 10 [Company], [Year], [Amount], LEAD(Amount, 1) OVER ( PARTITION BY Company ORDER BY Year DESC ) AS Lead_amount FROM [CompanySales] ;
My Personal Notes arrow_drop_up
Please Login to comment...