"GROUP BY" - Dividing Query Output into Multiple Groups in SQL Server

Q

How To Divide Query Output into Multiple Groups with the GROUP BY Clause in SQL Server?

✍: FYIcenter.com

A

Sometimes, you want to divide the query output into multiple groups, and apply group functions on each individual groups. Dividing query output into multiple groups can be done with the GROUP BY clause. Here is the syntax of a SELECT statement with a GROUP BY clause.

SELECT group_level_fields FROM source_tables
   WHERE search_condition
   GROUP BY group_by_expression 
  • group_by_express - An list of columns to be used as the group criteria - Rows that have the same combination of values of there columns form a single group.
  • group_level_fields - An list of selection expressions that can be evaluated at the group level.

The final output of the SELECT statement is the resulting values of group_level_fields for each group.

The following script gives you a good GROUP BY example with a single column as the group_by_expression. In this case, rows with the same value of this column will be considered as a single group.

SELECT tag, COUNT(*), MAX(counts), MIN(created) 
   FROM fyi_links GROUP BY tag
GO
tag     COUNT(*) MAX(counts)  MIN(created)
DBA     3        972          2005-01-01
DEV     2        439          2004-01-01
SQA     2        828          2003-01-01

Notice that, column "tag" can also be used in group_level_fields, because it is used as the group_by_expression, and becomes a constant for any given group.

 

HAVING - Apply Filtering Criteria at Group Level in SQL Server

Mixing Group Functions with Non-group Selection Fields in SQL Server

Using SELECT Statements and GROUP BY Clauses in SQL Server

⇑⇑ SQL Server Database Tutorials

2016-10-25, 2969🔥, 0💬