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.

  

 

 

How to use the Count() function with the DISTINCT predicate

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


 

The count() function with DISTINCT

Count the number of unique orders from customers

Discussion:

The previous example is fine, but we need to find a way to count the number of unique orders in this table.  The proper way to accomplish this task in SQL is to use the COUNT and DISTINCT statements together as: 

SELECT Count (Distinct orderid) as NumberofOrders FROM tbls_cusotmersag 

This is excellent, but our problem is that it does not work in Access 2007.  We need to deviate thematically for a second and use a subquery with DISTINCT to achieve the result we want.  (See chapter 30 on subqueries for a detailed explanation of how they work).  From the result set below, please notice that the number of orders produced by the count() function is now 15.  This is actually the number of unique orders in the table, which is exactly what we need. 

Code:

SELECT Count(*) AS NumberofOrders

FROM

(SELECT DISTINCT orderid FROM tbls_customersag)
 

Result: