Types of Window functions-
- Aggregate Window Functions
SUM(), MAX(), MIN(), AVG(). COUNT()
- Ranking Window Functions
RANK(), DENSE_RANK(), ROW_NUMBER(), NTILE()
- Value Window Functions
LAG(), LEAD(), FIRST_VALUE(), LAST_VALUE()
Syntax of Window Functions-
window_function ( [ ALL ] Expression )
OVER ( [ PARTITION BY partition_list ] [ ORDER BY order_list] )
Parameter Explanation
window_function: It indicates the name of your window function.
ALL: It is an optional keyword that is used to count all values along with duplicates. We cannot use the DISTINCT keyword in window functions.
Expression: It is the name of the column or expression on which window functions is operated. In other words, it is the column name for which we calculate an aggregated value.
OVER: It specifies the window clauses for aggregate functions. It mainly contains two expressions partition by and order by, and it always has an opening and closing parenthesis even there is no expression.
PARTITION BY partition_list: This clause divides the rows into partitions, and then a window function is operated on each partition. Here we need to provide columns for the partition after the PARTITION BY clause. If we want to specify more than one column, we must separate them by a comma operator. SQL Server will group the entire table when this clause is not specified, and values will be aggregated accordingly.
ORDER BY order_list: It is used to specify the order of rows within each partition. When this clause is not defined, SQL Server will use the ORDER BY for the entire table.
Here is an example of how to use the ROW_NUMBER() window function to assign a unique number to each row within a result set, starting at 1 for the first row:
Example-
Table-students
Student_name | Age | Subject | Marks |
Ajay | 10 | Math | 50 |
Bjay | 15 | Hindi | 30 |
Cjay | 12 | Math | 50 |
Djay | 18 | Math | 20 |
Ejay | 12 | Hindi | 20 |
Find the average marks of students for each subject and order students within a subject by age.
SELECT Student_name, Age, Subject, Marks,
AVG(Marks) OVER(PARTITION BY Subject ORDER BY Age) AS Avg_Marks
FROM students;
Student_name | Age | Subject | Marks | Avg_Marks |
Ajay | 10 | Math | 50 | 40 |
Cjay | 12 | Math | 50 | 40 |
Djay | 18 | Math | 20 | 40 |
Ejay | 12 | Hindi | 20 | 25 |
Bjay | 15 | Hindi | 30 | 25 |