GROUP BY
Group rows by one or more columns and apply aggregate functions to each group:GROUP BY 1, 2 groups by the first and second
select-list expressions:
HAVING
Filter groups after aggregation. You can use both aggregate and non-aggregate predicates:Aggregate Functions
| Function | Description |
|---|---|
COUNT(*) | Count all rows in the group |
COUNT(col) | Count non-NULL values in col |
SUM(col) | Sum of non-NULL values |
AVG(col) | Average of non-NULL values |
MIN(col) | Minimum value |
MAX(col) | Maximum value |
STDDEV(col) | Population standard deviation |
DISTINCT Aggregates
Deduplicate values before aggregating:Using Aliases in ORDER BY
Aliases defined in theSELECT list are available in ORDER BY. They cannot be used in GROUP BY or HAVING — repeat the expression there instead.
GROUPING SETS
GROUPING SETS lets you compute aggregates for multiple grouping combinations in a single query. Columns not part of a given grouping set are returned as NULL:
ROLLUP
ROLLUP creates subtotals that roll up from the most detailed level to a grand total. ROLLUP(a, b) is equivalent to GROUPING SETS((a, b), (a), ()):
CUBE
CUBE generates subtotals for all possible combinations of the grouping columns. CUBE(a, b) is equivalent to GROUPING SETS((a, b), (a), (b), ()):
Not Supported
- Window functions (
ROW_NUMBER,RANK,SUM OVER, etc.)