? Window Functions ?
? Window Functions ?
Ranking Functions
ROW_NUMBER()
RANK()
DENSE_RANK()
Distribution Functions
PERCENT_RANK()
CUME_DIST()
NTILE(n)
Aggregate Functions
SUM()
Rupal Agarwal
AVG():
COUNT():
MIN():
MAX()
Offset Functions
LAG()
LEAD()
FIRST_VALUE()
LAST_VALUE()
WINDOW FUNCTIONS
A window function performs a calculation across a set of table rows that are somehow related
to the current row. This is comparable to the type of calculation that can be done with an
aggregate function. But unlike regular aggregate functions, use of a window function does not
cause rows to become grouped into a single output row — the rows retain their separate
identities.
Let's consider the example of a sales table and show both the input data and the output results
for various window function queries.
1. ROW_NUMBER()
Assigns a unique sequential integer to rows within a partition of a result set, starting with 1 for
the first row in each partition.
FROM sales;
Assigns a rank to each row within a partition of a result set. The rank of a row is one plus the
number of ranks that come before it.
FROM sales;
3. DENSE_RANK()
Similar to RANK(), but does not skip ranks if there are ties.
FROM sales;
Divides the rows in an ordered partition into a specified number of approximately equal groups, and
assigns a number to each group.
SELECT salesperson_id,order_date,revenue,
FROM sales;
5. LAG()
Provides access to a row at a given physical offset that comes before the current row.
FROM sales;
Provides access to a row at a given physical offset that comes after the current row.
FROM sales;
7. FIRST_VALUE()
FROM sales;
FROM sales;
You can also use aggregate functions as window functions to calculate running totals, moving averages,
etc.
from sales;
10. Percent_rank
It calculates the relative rank of a row within a group of rows. This rank is expressed as a percentage
between 0 and 1, representing the position of the row in relation to other rows in the result set.
/* formula=current_row-1/Total_no_of_rows-1 */
It calculates the cumulative distribution of a value in a set of values. It returns the proportion of rows
that have a value less than or equal to the current row's value, relative to the total number of rows. The
result is a value between 0 and 1.