10.12.2012 Views

Application Programming and SQL Guide - Kmlinux

Application Programming and SQL Guide - Kmlinux

Application Programming and SQL Guide - Kmlinux

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

|<br />

|<br />

|<br />

#<br />

#<br />

#<br />

#<br />

#<br />

#<br />

Summarizing group values: GROUP BY<br />

Use GROUP BY to group rows by the values of one or more columns or by the<br />

results of an expression. You can then apply aggregate functions to each group.<br />

Except for the columns that are named in the GROUP BY clause, the SELECT<br />

statement must specify any other selected columns as an oper<strong>and</strong> of one of the<br />

aggregate functions.<br />

Example: GROUP BY clause using one column: The following <strong>SQL</strong> statement<br />

lists, for each department, the lowest <strong>and</strong> highest education level within that<br />

department:<br />

SELECT WORKDEPT, MIN(EDLEVEL), MAX(EDLEVEL)<br />

FROM DSN8810.EMP<br />

GROUP BY WORKDEPT;<br />

If a column that you specify in the GROUP BY clause contains null values, DB2<br />

considers those null values to be equal. Thus, all nulls form a single group.<br />

When it is used, the GROUP BY clause follows the FROM clause <strong>and</strong> any WHERE<br />

clause, <strong>and</strong> precedes the ORDER BY clause.<br />

You can group the rows by the values of more than one column.<br />

Example: GROUP BY clause using more than one column: The following<br />

statement finds the average salary for men <strong>and</strong> women in departments A00 <strong>and</strong><br />

C01:<br />

SELECT WORKDEPT, SEX, AVG(SALARY) AS AVG_SALARY<br />

FROM DSN8810.EMP<br />

WHERE WORKDEPT IN (’A00’, ’C01’)<br />

GROUP BY WORKDEPT, SEX;<br />

The result table looks similar to the following output:<br />

WORKDEPT SEX AVG_SALARY<br />

======== === ==============<br />

A00 F 49625.00000000<br />

A00 M 35000.00000000<br />

C01 F 29722.50000000<br />

DB2 groups the rows first by department number <strong>and</strong> then (within each department)<br />

by sex before it derives the average SALARY value for each group.<br />

You can also group the rows by the results of an expression<br />

Example: GROUP BY clause using a expression: The following statement groups<br />

departments by their leading characters, <strong>and</strong> lists the lowest <strong>and</strong> highest education<br />

level for each group:<br />

SELECT SUBSTR(WORKDEPT,1,1), MIN(EDLEVEL), MAX(EDLEVEL)<br />

FROM DSN8810.EMP<br />

GROUP BY SUBSTR(WORKDEPT,1,1);<br />

Chapter 1. Retrieving data 11

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!