2. +
Introduction
Window aggregate functions are the same as the group
aggregate functions (for example, SUM, COUNT, AVG, MIN,
and MAX), except window aggregate functions are applied to a
window of rows defined by the OVER clause;
Benefit: windower queries do not hide the detail. A row for
every row;
Using the OVER clause you define a set of rows for the
function to work with per each underlying row.
4. +
Example 1
Description
Here’s an example of a query against the Sales.OrderValues view
returning for each order the customer ID, order ID, and order value;
using window functions, the query also returns the grand total of all
values and the customer total.
Two differences: the grand total is of course the same for all rows
(we are using over with empty parentheses) . The customer total is
the same for all rows with the same customer ID
5. +
Framing
Window aggregate functions support another filtering option
called framing.
Idea: you define ordering within the partition by using a window
order clause, and then based on that order, you can confine a
frame of rows between two delimiters. You define the delimiters
by using a window frame clause.
Requirement: a window order clause to be present because a
set has no order, and without order, limiting rows between two
delimiters would have no meaning
6. +
Framing
You have to define frame units (rows or range) and the
delimiters.
With the ROWS window frame unit, you can indicate the
delimiters as one of three options:
UNBOUNDED PRECEDING or FOLLOWING, meaning the
beginning or end of the partition, respectively
CURRENT ROW, obviously representing the current row
ROWS PRECEDING or FOLLOWING, meaning n rows before or
after the current, respectively
8. +
Example 2
Description
Observe how the values keep accumulating from the beginning of
the customer partition until the current row;
Because window functions are supposed to operate on the
underlying query’s result set, they are allowed only in the SELECT
and ORDER BY clauses;
If you need to refer to the result of a window function in any clause
that is evaluated before the SELECT clause, you need to use
a table expression.