GROUP BY Clause (SELECT Statement)

The GROUP BY clause groups identical output values in the named columns. Every value expression in the output column that includes a table column must be named in it unless it is an argument to aggregate functions. GROUP BY is used to apply aggregate functions to groups of rows defined by having identical values in specified columns.

If you don't use GROUP BY, either all or none of the output columns in the SELECT clause must use aggregate functions. If all of them use aggregate functions, all rows satisfying the WHERE clause or all rows produced by the FROM clause (if there is no WHERE clause) are treated as a single group for deriving the aggregates.

The GROUP BY clause defines groups of output rows to which aggregate functions (COUNT, MIN, AVG, and so on) can be applied. If you do not use this clause and elect to use aggregate functions, the column names in the SELECT clause must all be contained in aggregate functions, and the functions are applied to all rows to satisfy the query.

Otherwise, each column referenced in the SELECT list outside an aggregate function must be a grouping column and be referenced in this clause. All rows output from the query that have all grouping column values equal, constitute a group. (For the purposes of GROUP BY, all NULLs are considered equal). The aggregate function is applied to each such group.