O'Reilly logo

Microsoft SQL Server 2012 Bible by Aaron Nelson, Jose Chinchilla, Patrick LeBlanc, Jorge Segarra, Adam Jorgensen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Grouping Within a Result Set

Aggregate functions are all well and good, but how often do you need a total for an entire table? Most aggregate requirements include a date range, department, type of sale, region, or the like. That presents a problem. If the only tool to restrict the aggregate function were the WHERE clause, then database developers would waste hours replicating the same query, or writing a lot of dynamic SQL queries and the code to execute the aggregate queries in sequence.

Fortunately, aggregate functions are complemented by the GROUP BY function, which automatically partitions the data set into subsets based on the values in certain columns. When the data set is divided into subgroups, the aggregate functions are performed on each subgroup.

Simple Groupings

Using the GROUP BY clause to complement the aggregate functions provides the ability to include descriptive columns to the result. For example, in the following query the GROUP BY clause is included in the query to slice the data by Country or Region Code:

USE AdventureWorks;

SELECT 
  st.CountryRegionCode,
  SUM(TotalDue) TotalSalesDue
FROM Sales.SalesOrderHeader soh
INNER JOIN Sales.SalesTerritory st
  ON soh.TerritoryID = st.TerritoryID
GROUP BY
  st.CountryRegionCode

Result:

CountryRegionCode TotalSalesDue
----------------- ---------------------
AU        11814376.0952
CA        18398929.188
DE        5479819.5755
FR        8119749.346
GB        8574048.7082
US        70829863.203

The first column of this query returns the CountryRegionCode column. Although ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required