Stats

299 Contributors: 15
2017-03-22
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

GROUP BY

Download sql eBook

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 ] )

Related Examples