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


  

Section Menu 

Are you a University or College bookstore and want to order multiple books?  Email us at alphapress@hotmail.com or call us at 518-250-3890.  We will be happy to talk to you.  

Are you a professor and you need a sample copy?  We will be happy to send you a pdf or printed copy!  Email us at alphapress@hotmail.com.

Are you outside the United States?  We can ship multiple books worldwide in most countries.

  

 

 

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: