Page 104 - SQL
P. 104
Chapter 29: GROUP BY
Introduction
Results of a SELECT query can be grouped by one or more columns using the GROUP BY
statement: all results with the same value in the grouped columns are aggregated together. This
generates a table of partial results, instead of one result. GROUP BY can be used in conjunction
with aggregation functions using the HAVING statement to define how non-grouped columns are
aggregated.
Syntax
• GROUP BY {
column-expression
| ROLLUP ( <group_by_expression> [ ,...n ] )
| CUBE ( <group_by_expression> [ ,...n ] )
| GROUPING SETS ( [ ,...n ] )
| () --calculates the grand total
} [ ,...n ]
• <group_by_expression> ::=
column-expression
| ( column-expression [ ,...n ] )
• <grouping_set> ::=
() --calculates the grand total
| <grouping_set_item>
| ( <grouping_set_item> [ ,...n ] )
• <grouping_set_item> ::=
<group_by_expression>
| ROLLUP ( <group_by_expression> [ ,...n ] )
| CUBE ( <group_by_expression> [ ,...n ] )
Examples
USE GROUP BY to COUNT the number of rows for each unique entry in a
given column
Let's say you want to generate counts or subtotals for a given value in a column.
Given this table, "Westerosians":
https://riptutorial.com/ 86

