Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

GROUP BY function giving inaccurate Count figures 1

Status
Not open for further replies.

MustangPriMe

IS-IT--Management
Oct 9, 2002
74
GB
I've apparently forgotten how to use the GROUP BY clause effectively.

I have 3 tables relating to each other - tblCompanies, tblSites and tblContacts.

tblCompanies
- fldCompanyID
- fldCompanyName
- etc

tblSites
- fldSiteID
- fldOwningCompanyID
- fldAddress
- etc

tblContacts
- fldContactID
- fldOwningSiteID
- fldName
- fldContactArchived
- etc

I'm trying to query the database to list how many sites per company have non-archived (or live) contacts

I'm using..

SELECT tblSites.fldOwningCompanyID, Count(tblSites.fldSiteID) AS CountOffldSiteID
FROM tblContacts INNER JOIN tblSites ON tblContacts.fldOwningSiteID = tblSites.fldSiteID
WHERE (tblContacts.fldContactArchived=0)
GROUP BY tblSites.fldOwningCompanyID;

.. which returns a company ID per row, but gives the count of live contacts for each company instead of the number of sites which have live contacts for each company.

I can't think where I'm going wrong. The only thing I can think is that it's something to do with the fact that the tables are actually linked tables from an SQL database, and for some reason the GROUP BY clause is not working in the same way.
Can anyone put me out of my misery?
 
JetSQL lacks the Count(DISTINCT ...) aggregate function.
A workaround:
SELECT S.fldOwningCompanyID, Count(*) AS CountOffldSiteID
FROM tblSites AS S INNER JOIN (
SELECT DISTINCT fldOwningSiteID FROM tblContacts WHERE fldContactArchived=0
) AS D ON S.fldSiteID = D.fldOwningSiteID
GROUP BY S.fldOwningCompanyID

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Excellent! Have a star!

I'm not sure how I haven't come across this before.
Do you know the reason for this behaviour? Is it because I have a linked table 'below' the one I'm trying to Group by?

Thanks
Paul
 
The explanation is in the first line of my previous reply.
In ANSI SQL you may simply do this:
SELECT S.fldOwningCompanyID, COUNT(DISTINCT C.fldOwningSiteID) AS CountOffldSiteID
FROM tblSites AS S
INNER JOIN tblContacts AS C ON S.fldSiteID = C.fldOwningSiteID
WHERE C.fldContactArchived = 0
GROUP BY S.fldOwningCompanyID

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top