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 issue of uniqueness of values in crosstab queries

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


 

The issue of uniqueness of values in crosstab queries

Find total sales by customer and year

Discussion:

Now, our supervisor asks for additional detail.  Specifically, he wants a sales report by customer and year.  Again, in a few seconds, we replace the city field from the previous example with lastname and presumably, we are done! 

Unfortunately, that isn’t the case this time!  Our problem is that multiple customers might have the same last names.  Since we are grouping on the last name field, all of the customers with the same lastname will be grouped together!  This is a very common problem in crosstab queries and when using the GROUP BY clause.  Consequently, I would like you to develop a process to think thoroughly about the uniqueness of values when using the GROUP BY clause.  For instance, you should think about the possibility of having the same last name in your data for multiple customers.  The same is true for city fields since the same city name might refer to multiple distinct cities, as is the case with Portland, Oregon and Portland, Maine.  We will see how we can solve this problem in the next example with concatenated fields. 

In addition, notice from the result set that there are some blank values.  For example, there is a blank value for Ames in 2008 and Andersen in 2009.  These blanks mean that Ames and Andersen have not placed any orders in 2008 and 2009 respectively.  This is not a problem at all.

Design Code:

 

Code:

TRANSFORM sum([unitprice]*[quantity]) AS Ordertotal

SELECT lastname

FROM Qry_Crosstab_Base

GROUP BY lastname

PIVOT year([OrderDate])
 

Result: