AlphaPress Publishing
P.O. Box 5942 Albany, NY 12205
Tel: 518-250-3890
Email: alphapress@hotmail.com  


  
Click to buy this book from Amazon

Section Menu 

News

Pindaro is now working on a comprehensive book on SQL Server 2014.  For any comments you can email the author at alphapress@hotmail.com.

  

 

 

The GROUP BY clause with one aggregated field and WHERE

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


The GROUP BY clause on one column, one aggregated field, and WHERE

Find total order amounts for a subset of customers

Discussion:

Sometimes, we want to exclude certain records from our aggregate calculations.  In these cases, we can use the WHERE clause to exclude records we are not interested in working with.  Using WHERE, we exclude records before the GROUP BY clause takes effect.  Therefore, if we have a source dataset with 3,000 records and use WHERE, the GROUP BY clause takes effect on the remaining records only.  Later, you will learn the use of HAVING, which is a filtering statement like WHERE that takes effect after the GROUP BY calculates the summarized field values.  Consequently, you need to know exactly what you want to do and use the appropriate filtering statement with GROUP BY. 

In this example, we look for order totals by customer, but we want to exclude the orders from our customer Spicer.  Mr. Spicer has only one order with orderid = 509.  We use three fields in this SQL statement:  Lastname, OrderTotal, and OrderID.  LastName is the GROUP BY field, OrderTotal the aggregated field, and OrderID the filtering field. 

Code:

SELECT LastName, SUM(unitprice*quantity) AS OrderTotal

FROM tbls_customersgr

WHERE orderid <> 509

GROUP BY LastName
 

Result: