Window Aggregate Functions
Window functions operate on a set of rows and return a single value for each row from the underlying query. Like aggregate functions, window functions operate on a set of rows, but they do not reduce the number of rows returned by the query.
Unlike regular aggregate functions, window functions do not group rows into a single output row. Instead, the rows retain their separate identities, and the window function produces aggregate calculations that access more than just the current row in the query result.
The term window describes the set of rows on which the window function operates. A window function returns a value from the rows in a window.
The database uses the ORDER BY and PARTITION BY clauses to define the scope of the window.
Syntax
Window Aggregate functions follow this syntax with window_function representing any of the functions listed in Supported Window Aggregate Functions.
Window Aggregate Keywords
Window aggregate functions use these clauses and keywords to designate the parameters for the query and output.
PARTITION BY
This clause defines a set of rows within a result set. PARTITION BY operates similarly to a GROUP BY clause, except it does not reduce the number of rows in the result set.
ORDER BY
Sorts the result set in ascending or descending order based on one or more specified columns.
An ORDER BY clause must be included on all window functions to ensure your query results are deterministic. Some window functions require an ORDER BY clause. See the syntax for each function for specifics. For details, see ORDER BY.
ASC or DESC
Specifies whether the values in the specified column should be sorted in ASC ascending or DESC descending order. ASC is the default sort order.
NULLS FIRST, NULLS LAST, or IGNORE NULLS
Specifies if the database sorts NULL rows first NULLS FIRST, last NULLS LAST, or whether the database ignores NULLs IGNORE NULLS. The default is NULLS LAST.
ROWS or RANGE
Limit the rows within the partition by specifying start and end points within the partition. Specify a range of rows with respect to the current row by logical association using RANGE or physical association using ROWS.
The RANGE clause logically limits the rows within a partition by specifying a range of values with respect to the value in the current row. The system defines preceding or following rows based on the ordering in the ORDER BY clause. If you do not specify this clause, the default is ascending order.
The ROWS clause limits the rows within a partition by specifying a fixed number of rows preceding or following the current row.
Specifying a window frame by the RANGE keyword with the current row CURRENT ROW keyword includes all rows with the same values as the current row in the ORDER BY clause.
ROWS and RANGE clauses can include these options.
Supported Window Aggregate Functions
These functions are supported for window frames. Some examples use the sys.dummy virtual table to populate data. For details, see Generate Tables Using sys.dummy.
You cannot use the DISTINCT keyword with window aggregation functions.
CUME_DIST
Returns a positive value less than one that represents a percentage of values that are less than or equal to the current value in the group.
Syntax
Example
This example shows the cumulative distribution values for a table with generated numbers from one to 10.
Output
DELTA
Computes the finite difference between successive values of expression under the specified ordering. This is a backward difference, meaning the delta value for a specified row is the difference between the value of that row and the previous row.
The function requires two rows of input data to calculate a first-degree difference, three rows of input data to calculate a second-degree difference, and so on.
However, rather than returning NULL for the first few rows, the function returns the correct values, such that using DELTA of degree n followed by DELTA of degree -n cancel each other out to return the initial result (other than floating point error accumulation). In general, using this window function over larger result sets with large degrees worsens floating-point error accumulation.
Integer degree values in the range [-3, 3] are generally stable up to approximately 5 million rows. Fractional degree values in the range [-3, 3] are generally stable up to approximately 1 million rows. The stable degree range is wider over smaller result sets and narrower over larger result sets. For example, fractional and integer degrees are stable over the range [-4, 4] up to approximately 80,000 rows.
The function treats any NULL values in the input data as zero, which might cause unexpected results. Filter out NULL values before you use the window function.
Syntax
Examples
Calculate Difference Values Using****Basic Numbers
This example shows the delta values for a table with generated numbers from one to 10.
Output
Calculate Difference Values Using Partitioned Sales Data
This example uses the DELTA function with a table of regional sales data to find the difference in sales by region and year.
Output
DENSE_RANK
Assigns a rank to each row in the result set with equal values having the same number. There are no gaps between ranks.
Syntax
Example
This example generates the rank for a series of ten random numbers. Use the RAND function to generate the random numbers.
Output
DERIVATIVE
The function calculates the difference between successive values of two numeric expressions, representing a backward difference (e.g., the difference between the current and previous row). It can be considered as computing the derivative of one expression with respect to another.
The function must use an ORDER BY clause, and it cannot use a PARTITION BY clause.
DERIVATIVE requires two arguments, expression and expression2, which must be included in the ORDER BY clause.
The function computes the difference in expression values between consecutive rows and divides this by the difference in expression2 values over the same rows. If expression represents some measured value and expression2 is time, the result is the rate of change (derivative) of the value with respect to time.
The function can compute higher-degree derivatives (second, third, etc.). To calculate the nth-degree derivative, it uses a backward difference formula that compares the current row to the previous n rows.
For example:
- A second-degree derivative requires three rows of data: the current row, the previous row, and the one before the previous row.
- A third-degree derivative would require four rows, and so on.
Unlike some functions that return NULL for rows that lack sufficient preceding data, the DERIVATIVE function is designed to return correct values even for initial rows. This behavior ensures that if you apply a derivative of degree n followed by its inverse (derivative of degree -n), you recover the original values with minimal error (except for floating point inaccuracies).
In general, using this function over larger result sets with larger degrees worsens the floating-point error. Integer degree values in the range of three are generally stable up to approximately 5 million rows. Fractional degree values in the range of three are generally stable up to approximately 1 million rows. The stable degree range is wider over smaller result sets and narrower over larger result sets. For example, fractional and integer degrees are stable over the range [-4, 4] up to approximately 80,000 rows.
For higher-order calls, the sample points for expression must be equally spaced, or the function might return incorrect results. In other words, the DELTA executions between consecutive expression2 values must always be the same. If this is not true, use some form of interpolation to create an evenly-spaced series of samples before you use the window function.
The function treats any NULL values in the input data for either expression or expression2 arguments as zero, which might cause unexpected results. Filter out NULL values before you use the window function.
Syntax
Examples
Calculate the Derivative Using Basic Numbers
This example shows the derivative values for a basic table with values x and y.
Output
Calculate the Antiderivative Using a Negative Degree
This example uses a negative degree to produce an antiderivative.
Output
FIRST_VALUE
Returns the first value in the ordered result set.
Syntax
Example
This example uses a table with generated numbers from one to 10. Of this group, the function determines the first value from the ordering.
Output
LAG
Returns a row backward from the current row (one row back unless you specify a different number value).
For marking repeated LAG calls on one or more columns, see Data Preparation.
Syntax
Examples
Calculate Lag Using Basic Numbers
This example uses a table with generated numbers from one to 10. Of this group, the LAG function returns the last value for the specified column y.
Output
Calculate Lag Using an Offset
In this example, the offset value 5 changes the number of rows back from the current row from which to return a value.
Output
LAST_VALUE
Returns the last value in the ordered result set.
Syntax
Example
This example uses a table with generated numbers from one to 10. Of this group, the function determines the last value from the ordering.
Output
LEAD
Returns a row forward from the current row (one row forward unless you specify a different number value).
Syntax
Examples
Calculate the Lead Value Using Basic Numbers
This example uses a table with generated numbers from one to 10. Of this group, the LEAD function returns the last value for the specified column y.
Output
Calculate the Lead Value Using an Offset
In this example, using a table of generated numbers with values from one to 10, specify the offset value 5 in the LEAD function to change the number of rows forward from the current row to return a value.
Output
NTH_VALUE
Returns the n-th value in the ordered result set.
Syntax
Examples
Calculate the Fifth Value Using Bounded Rows
This example uses a table with generated numbers from one to 10. Of this group, the NTH_VALUE function returns the fifth value for the specified column y.
For the first four rows, the window contains fewer than five rows, so the function returns NULL because the fifth value is not yet available.
Output
Calculate the Fifth Value Using Unbounded Rows
To include future rows in the window frame, you can modify the window frame as shown in this example.
Output
PERCENTILE
Returns the value corresponding to the specified percentile (0 ≤ n ≤ 1) within the group.
The set of values is treated as a continuous distribution, so it is possible that the computed value cannot appear in the result set.
Syntax
Example
This example finds the value at approximately 90 percent of the range of the expression values. For the source data, use a table of generated numbers from one to 10.
The value returns 9.1 because the window column starts at 1. It would be 9 if the column started at 0.
Output
PERCENT_RANK
Returns a percentage value for each row representing the percentage of values less than the current group, excluding the highest value. The highest value in a group is always 1.
Syntax
Example
This example generates the percent rank of the table with ten generated numbers from one to 10.
Output
RANK
Assigns a rank number to each row in the result set with equal values having the same number. There can be gaps between ranks. Results are similar to the ranking used in sporting events.
Syntax
Example
This example ranks a series of ten random numbers. Use the RAND function to generate the random numbers.
Output
RATIO_TO_REPORT
Computes the ratio of a value to the sum of the set of values. For example, the RATIO_TO_REPORT function calculates the ratio of the salary of an employee relative to the total salaries in the department where the employee belongs.
Syntax
Example
This example shows a ratio of each salary of an individual employee to the total salaries.
Output
ROW_NUMBER
Assigns a unique number to each row in the result set.
Syntax
Examples
Determine the Unique Number of Each Row in a Table
This example assigns a row number to a basic table of fruit prices based on the price order.
Output
Determine the Unique Number of Each Row****Using a Partitioned Table
This example uses a table of sales data for two regions. The ROW_NUMBER function orders the sales team members by their region and sales amounts.
Output
ZSCORE
Calculates the z-score of the sample based on the standard deviation (similar to the STDDEV aggregate function).
The standard deviation assumes that the data is a sample of a larger set, meaning it corrects for bias.
If your data set is comprehensive and represents an entire group, use the ZSCOREP function instead.
Syntax
Example
This example calculates the standard deviation in a range of salaries.
Output
ZSCOREP
Calculates the z-score of the sample based on the population standard deviation (similar to the STDEVP aggregate function).
The population standard deviation assumes that the data contains the entire population, meaning there is no correction for bias. Use it when your data set is comprehensive and represents the entire group (i.e. population) you are analyzing.
If your data set is a sample of a larger set, use the ZSCORE function.
Syntax
Example
This example calculates the population standard deviation in a range of salaries.
Output

