我正在使用SQL Server 2008.
我有一个需要稍微调整的查询。当我计算与网站相关的品牌时,它非常适合,但当我尝试计算与品牌相关的模型时,网站数量会发生变化。
表格是
SITES
SiteID // pk
SiteName
BRANDS
BrandID // pk
SiteID // fk
Brand
MODELS
ModelID // pk
BrandID // fk
此查询生成与网站关联的正确的TotalBrands数量:
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
当我向查询添加更多内容时,TotalBrands是不准确的。
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
我想要包括所有网站,无论他们是否有品牌。我想要计算所有品牌是否有型号。我想要计算所有模型。
我的查询有什么问题?
答案 0 :(得分:3)
正如评论中所说的那样,你在上一个JOIN
上乘以结果。因此,您要么进行DISTINCT
计数,要么先进行分组。
SELECT S.SiteID,
S.SiteName,
COUNT(B.BrandID) AS TotalBrands,
SUM(M.Models) AS TotalModels
FROM Sites S
LEFT JOIN Brands B
ON S.SiteID = B.SiteID
LEFT JOIN ( SELECT BrandId, COUNT(*) Models
FROM Models
GROUP BY BrandId) M
ON B.BrandID = M.BrandID
GROUP BY S.SiteID, S.SiteName
或者
SELECT S.SiteID,
S.SiteName,
COUNT(DISTINCT 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