I am using SQL Server 2008.
I have a query that needs a little tweaking. It counts perfectly well when I count The Brands that are associated with the Sites, but when I try to count the Models that are associated with the brands, the number of sites changes.
The tables are
SITES
SiteID // pk
SiteName
BRANDS
BrandID // pk
SiteID // fk
Brand
MODELS
ModelID // pk
BrandID // fk
This query yields the correct number of TotalBrands associated with a site:
SELECT S.SiteID,
S.SiteName,
COUNT(B.BrandID) AS TotalBrands
FROM Sites S
LEFT JOIN Brands B
ON S.SiteID = B.SiteID
GROUP BY S.SiteID, S.SiteName
When I add a little bit more to the query, the TotalBrands is inaccurate.
SELECT S.SiteID,
S.SiteName,
COUNT(B.BrandID) AS TotalBrands,
COUNT(M.ModelID) AS TotalModels
FROM Sites S
LEFT JOIN Brands B
ON S.SiteID = B.SiteID
LEFT JOIN Models M
ON B.BrandID = M.BrandID
GROUP BY S.SiteID, S.SiteName
I want to include all sites, whether they have Brands or not. I want to count all Brands whether they have Models or not. I want to count all Models.
What’s wrong with my query?
As was said in the comments, you are multipliying results on your last
JOIN. So you etiher do aDISTINCTcount, or do the grouping before.Or