WEIGHTED_AVG function [Aggregate]

Function

Calculates an arithmetically (or linearly) weighted average. A weighted average is an average in which each quantity to be averaged is assigned a weight. Weightings determine the relative importance of each quantity that make up the average.

Syntax

WEIGHTED_AVG (expression)
OVER (window-spec)

window-spec: See the Usage section, below.

Parameters

expression A numeric expression for which a weighted value is being computed.

Usage

Use the WEIGHTED_AVG function to create a weighted moving average. In a weighted moving average, weights decrease arithmetically over time. Weights decrease from the highest weight for the most recent data points, down to zero.

Figure 4-2: WEIGHTED_AVG calculation

WEIGHTED_AVG calculation

To exaggerate the weighting, you can average two or more weighted moving averages together, or use an EXP_WEIGHTED_AVG function instead.

You can specify elements of window-spec either in the function syntax (inline), or with a WINDOW clause in the SELECT statement.

window-spec:

For information on how to specify the window, see “Analytical functions”.

Example

The following example returns a weighted average of salaries by department for employees in Florida, with the salary of recently hired employees contributing the most weight to the average:

SELECT DepartmentID, Surname, Salary,
WEIGHTED_AVG(Salary) OVER (PARTITION BY DepartmentID
ORDER BY YEAR(StartDate) DESC) as "W_AVG"
FROM Employees
WHERE State IN ('FL') ORDER BY DepartmentID

The returned result set is:

Table 4-63: WEIGHTED_AVG result set

DepartmentID

Surname

Salary

W_AVG

100

Lull

87900.000

87900.000000

100

Gowda

59840.000

69193.333333

200

Sterling

64900.000

64900.000000

200

Kelly

87500.000

79966.666667

300

Litton

58930.000

58930.000000

400

Evans

68940.000

68940.000000

400

Charlton

28300.000

41846.666667

400

Francis

53870.000

47858.333333

Standards and compatibility