Calculation of aggregate values
You can use the SQL aggregate functions to calculate values that are based on entire columns of data. The calculated values are from only the rows that satisfy the WHERE clause and are therefore selected.
An aggregate function is an operation that derives its result by using values from one or more rows. An aggregate function is also known as a column function. The argument of an aggregate function is a set of values that are derived from an expression.
You can use the following aggregate functions:
- SUM
- Returns the total value.
- MIN
- Returns the minimum value.
- AVG
- Returns the average value.
- MAX
- Returns the maximum value.
- COUNT
- Returns the number of selected rows.
- COUNT_BIG
- Returns the number of rows or values in a set of rows or values. The result can be greater than the maximum value of an integer.
- XMLAGG
- Returns a concatenation of XML elements from a collection of XML elements.
SELECT SUM(SALARY) AS SUMSAL,
MIN(SALARY) AS MINSAL,
AVG(SALARY) AS AVGSAL,
MAX(SALARY) AS MAXSAL,
COUNT(*) AS CNTSAL
FROM EMP
WHERE DEPT = 'A00';
The result table looks like this:
SUMSAL MINSAL AVGSAL MAXSAL CNTSAL
========= ======== ============== ======== ======
128500.00 29250.00 42833.33333333 52750.00 3
You can use (*) in the COUNT and COUNT_BIG functions. In this example, COUNT(*) returns the rows that DB2® processes based on the WHERE clause.
SELECT COUNT(*)
FROM EMP;
You can use DISTINCT with the SUM, AVG, COUNT, and COUNT_BIG functions. DISTINCT means that the selected function operates on only the unique values in a column.
SELECT COUNT(DISTINCT JOB)
FROM EMP;
Aggregate functions like COUNT ignore nulls in the values on which they operate. The preceding example counts distinct job values that are not null.
You can use SUM and AVG only with numbers. You can use MIN, MAX, COUNT, and COUNT_BIG with any built-in data type.