Aggregations (ORDER BY, GROUP BY, HAVING, SUM, COUNT, AVG, etc)
ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default.
Syntax
Example
Columns of type ntext, text, image, geography, geometry, and xml cannot be used in an ORDER BY clause.
GROUP BY
The GROUP BY statement group rows that have the same values into summary rows
It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
Syntax
Example
GROUP BY ROLLUP
Creates a group for each combination of column expressions. In addition, it "rolls up" the results into subtotals and grand totals.
For example, GROUP BY ROLLUP (col1, col2, col3, col4)
creates groups for each combination of column expressions in the following lists.
col1, col2, col3, col4
col1, col2, col3, NULL
col1, col2, NULL, NULL
col1, NULL, NULL, NULL
NULL, NULL, NULL, NULL --This is the grand total
GROUP BY CUBE
GROUP BY CUBE creates groups for all possible combinations of columns.
For GROUP BY CUBE (a, b) the results has groups for unique values of (a, b), (NULL, b), (a, NULL), and (NULL, NULL).
HAVING
Specifies a search condition for a group or an aggregate.
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
Syntax
Example
SUM
Returns the sum of all the values, or only the DISTINCT values, in the expression.
SUM can be used with numeric columns only. Null values are ignored.
Syntax
Example
COUNT
This function returns the number of items found in a group. This includes NULL values and duplicates.
COUNT
is a deterministic function when used without the OVER and ORDER BY clauses.
Syntax
Example
AVG
This function returns the average of the values in a group. It ignores null values.
Syntax
Example
Last updated