AVG
Description
The AVG
function is used to calculate the average value of an expression within a window. This function can be applied to various numeric data types, including TINYINT
, SMALLINT
, INT
, BIGINT
, FLOAT
, DOUBLE
, and DECIMAL
. The type of the return result will be converted accordingly based on the input type. Results of the DECIMAL
type will retain their original precision and scale, while other types will return as DOUBLE
. It is important to note that NULL
values will not be included in the average calculation.
Syntax
Parameter Description
expr
: The numeric expression for which the average value needs to be calculated.PARTITION_clause
: Optional parameter used to partition the data so that the average value is calculated separately within each partition.ORDER_BY_clause
: Optional parameter used to specify the sorting method of records within the window.FRAME_clause
: Optional parameter used to define the specific range of the window.
Return Result
The AVG
function returns a numeric value representing the average value of the data within the window. For DECIMAL
type, the return result is also of DECIMAL
type, and its precision and scale may increase. The return result for other types is of DOUBLE
type.
Example
- Query the average salary (
salary
) of the same department (dep_no
), partitioned by department without sorting:
The result is as follows:
- Query the cumulative average salary (
salary
) of the same department (dep_no
), partitioned by department and ordered by salary. Return the average value from the start row to all rows with the same salary as the current row in the current window:
The result is as follows:
Notes
- When there are no non-
NULL
values within the window, theAVG
function returnsNULL
. - When using the
AVG
function, ensure that the definitions of partition, sorting, and window range meet expectations.