Summarizing group values
You can group rows in the result table by the values of one or more columns or by the results of an expression. You can then apply aggregate functions to each group.
Procedure
To summarize group values:
Use the GROUP BY clause.
When it is used, the GROUP BY clause follows the FROM clause and any WHERE clause, and it precedes the ORDER BY clause.
Except for the columns that are named in the GROUP BY clause, the SELECT statement must specify any other selected columns as an operand of one of the aggregate functions.
If a column that you specify in the GROUP BY clause contains null values, Db2 considers those null values to be equal. Thus, all nulls form a single group.
Examples
- Example: GROUP BY clause using one column
- The following SQL statement lists, for each department, the lowest and highest education level within that department:
SELECT WORKDEPT, MIN(EDLEVEL), MAX(EDLEVEL) FROM DSN8C10.EMP GROUP BY WORKDEPT; - Example: GROUP BY clause using more than one column
- You can group the rows by the values of more than one column. For example, The following statement finds the average salary for men and women in departments A00 and C01:
SELECT WORKDEPT, SEX, AVG(SALARY) AS AVG_SALARY FROM DSN8C10.EMP WHERE WORKDEPT IN ('A00', 'C01') GROUP BY WORKDEPT, SEX; - Example: GROUP BY clause using a expression
- You can also group the rows by the results of an expression. For example, the following statement groups departments by their leading characters, and lists the lowest and highest education level for each group:
SELECT SUBSTR(WORKDEPT,1,1), MIN(EDLEVEL), MAX(EDLEVEL) FROM DSN8C10.EMP GROUP BY SUBSTR(WORKDEPT,1,1);