10.window Functions
10.window Functions
BY
JANARDHANA BANDI
WINDOW FUNCTIONS
WINDOW FUNCTIONS
A window is a group of related rows. A window can consist of one, or multiple rows.
A window function is any function that operates over a window of rows.
RANK – Returns rank over a group of values, skips the series in case of duplicates
DENSE_RANK – Returns rank over a group of values, doesn’t skips the series in case of
duplicates
ROW_NUMBER – Returns a unique row number for each row within a group of values
LEAD – To get the next row information
LAG – To get the next row information
FIRST_VALUE – Returns the first value within an ordered group of values.
LAST_VALUE – Returns the last value within an ordered group of values.
NTH_VALUE – Returns the nth value within an ordered group of values.
RANK
Rank:
• Returns the rank of a value within an ordered group of values.
• The rank value starts at 1 and continues up sequentially.
• If two values are the same, they have the same rank but skips the next
sequence number.
• Used to assign rank numbers, find the top values etc.
Syntax:
Desne_Rank:
• Returns the rank of a value within a group of values, without gaps in the ranks.
• The rank value starts at 1 and continues up sequentially.
• If two values are the same, they have the same rank, but doesn’t skips the next
sequence number.
• Used to assign rank numbers, find the top values etc.
Syntax:
Row_Number:
• Returns a unique row number for each row within a window partition.
• The row number starts at 1 and continues up sequentially.
• If two values are the same, assigns row number randomly.
• Used to assign a sequence number irrespective of duplicates.
Syntax:
FROM EMPLOYEES;
WHICH ONE TO CHOOSE?
LEAD: Can fetch the value for a particular column from subsequent(next) row in the same
table/group after sorting in some order, without using a self join.
Syntax: LEAD ( col/expr, [ , <offset> , <default> ] )
OVER ( [ PARTITION BY <col/expr> ] ORDER BY <col/expr> [ { ASC | DESC } ] )
FIRST_VALUE, LAST_VALUE AND NTH_VALUE
FIRST_VALUE: Returns the first value within an ordered group of values.
Syntax: FIRST_VALUE( <col/expr> )
OVER ( [ PARTITION BY <col/expr> ] ORDER BY <col/expr> [ { ASC | DESC } ]
Janardhana Bandi