SQL GROUP BY

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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



Got any SQL Question?