Aggregate functions with window frames allow you to compute aggregate values (such as sums, averages, and counts) over a specific range of rows, called a frame, within a window of data. This feature is part of window functions in SQL and provides fine-grained control for complex analytical tasks.
Aggregate functions perform calculations across a set of rows, returning a single result. Common aggregate functions include:
Window frames define a subset of rows within a window (partitioned dataset) over which an aggregate function operates. A window frame can be dynamic, based on conditions like the current row’s position, making it powerful for advanced analytics.
A window frame is a range of rows relative to the current row. It can be bounded by specific positions or conditions.
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
RANGE BETWEEN 100 PRECEDING AND CURRENT ROW
GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW
The general syntax for using aggregate functions with window frames:
aggregate_function(column_name)
OVER (
[PARTITION BY column_name]
[ORDER BY column_name]
[ROWS | RANGE | GROUPS BETWEEN frame_start AND frame_end]
)
Common aggregate functions that support window frames:
SELECT EmployeeID, Name, Salary,
SUM(Salary) OVER (ORDER BY EmployeeID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningTotal
FROM Employees;
EmployeeID | Name | Salary | RunningTotal |
---|---|---|---|
1 | Alice | 5000 | 5000 |
2 | Bob | 6000 | 11000 |
3 | Charlie | 7000 | 18000 |
SUM(Salary)
computes the running total.UNBOUNDED PRECEDING
) to the current row.
SELECT EmployeeID, Name, Salary,
AVG(Salary) OVER (ORDER BY EmployeeID ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS MovingAvg
FROM Employees;
EmployeeID | Name | Salary | MovingAvg |
---|---|---|---|
1 | Alice | 5000 | 5000.00 |
2 | Bob | 6000 | 5500.00 |
3 | Charlie | 7000 | 6500.00 |
1 PRECEDING
).AVG
function calculates the moving average over the frame.
SELECT EmployeeID, Name, Salary,
MAX(Salary) OVER (ORDER BY EmployeeID ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MaxSalary
FROM Employees;
EmployeeID | Name | Salary | MaxSalary |
---|---|---|---|
1 | Alice | 5000 | 5000 |
2 | Bob | 6000 | 6000 |
3 | Charlie | 7000 | 7000 |
MAX
function computes the maximum salary in this range.SQL allows excluding rows explicitly with the EXCLUDE
clause
SUM(Salary) OVER (ORDER BY EmployeeID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW EXCLUDE CURRENT ROW)
This excludes the current row from the frame.
Frame bounds can use dynamic expressions for more flexibility:
ROWS BETWEEN N PRECEDING AND M FOLLOWING
Here, N
and M
can be dynamic values.
PARTITION BY
and ORDER BY
.ROWS
instead of RANGE
for better performance in most cases.Aggregate functions with window frames extend SQL's analytical capabilities by enabling fine-grained row-wise calculations. Whether you're calculating running totals, moving averages, or identifying ranges of values, window frames provide unmatched flexibility. Happy Coding!❤️