SQL-J Language Reference
Page 34 of 121

GROUP BY clause

A GROUP BY clause, part of a SelectExpression, groups a result into subsets that have matching values for one or more columns. In each group, no two rows have the same value for the grouping column or columns. NULLs are considered equivalent for grouping purposes.

You typically use a GROUP BY clause in conjunction with an aggregate expression.

Syntax

GROUP BY ColumnName [ , ColumnName ] *

ColumnName must be a column from the current scope of the query; there can be no columns from a query block outside the current scope. For example, if a GROUP BY clause is in a subquery, it cannot refer to columns in the outer query.

SelectItems in the SelectExpression with a GROUP BY clause must contain only aggregates or grouping columns.

ColumnName cannot be an expression (although the column name can be qualified by a correlation name given to the table), as per the SQL-92 standard. This makes it difficult to group by method invocations, which are expressions. To work around this, enclose the method invocation in a subquery. For example:

SELECT MAX(city_temperature), country_name
FROM
    (SELECT city.showTemperature(), city.getDisplayCountry()
    FROM Cities)
AS CT(city_temperature, country_name)
GROUP BY CT.country_name

GROUP BY clause Examples

-- find the average flying_timse of flights grouped by
-- airport
SELECT AVG (flying_time), orig_airport
FROM Flights
GROUP BY orig_airport

SELECT MAX(city), region
FROM Cities, Countries
WHERE Cities.country_ISO_code = Countries.country_ISO_code
GROUP BY region

-- group by an orderable Java data type
SELECT city, AVG(rainfall)
FROM ManyCities
GROUP BY city