|Previous Top Next|
Combines rows with column values in common into single rows.
GROUP BY column_reference [, column reference...]
Use a GROUP BY clause to combine rows with the same column values into a single row. The criteria for combining rows is based on the values in the columns specified in the GROUP BY clause. The purpose for using a GROUP BY clause is to combine one or more column values (aggregate) into a single value and provide one or more columns to uniquely identify the aggregated values. A GROUP BY clause can only be used when one or more columns have an aggregate function applied to them.
The value for the GROUP BY clause is a comma-separated list of columns. Each column in this list must meet the following criteria:
|•||Be in one of the tables specified in the FROM clause of the query.|
|•||Be in the SELECT clause of the query.|
|•||Cannot have an aggregate function applied to it.|
When a GROUP BY clause is used, all table columns in the SELECT clause of the query must meet at least one of the following criteria, or it cannot be included in the SELECT clause:
|•||Be in the GROUP BY clause of the query.|
|•||Be in the subject of an aggregate function.|
Literal values in the SELECT clause are not subject to the preceding criteria.
The distinctness of rows is based on the columns in the column list specified. All rows with the same values in these columns are combined into a single row (or logical group). Columns that are the subject of an aggregate function have their values across all rows in the group combined. All columns not the subject of an aggregate function retain their value and serve to distinctly identify the group. For example, in the SELECT statement below, the values in the SALES column are aggregated (totaled) into groups based on distinct values in the COMPANY column. This produces total sales for each company.
SELECT company, SUM(sales) AS TOTALSALES
GROUP BY company
ORDER BY company
A column may be referenced in a GROUP BY clause by a column correlation name, instead of actual column names. The statement below forms groups using the first column, COMPANY, represented by the column correlation name Co.
SELECT company AS Co, SUM(sales) AS TOTALSALES
GROUP BY Co
ORDER BY 1
|•||Derived values (calculated fields) cannot be used as the basis for a GROUP BY clause.|
|•||Column references cannot be passed to an GROUP BY clause via parameters.|
SELECT, when aggregate functions used