SQL - 如何计算其他表中的项?

时间:2011-08-23 01:07:36

标签: sql

我有一个表名BRANDS。我有另一张名为MODELS的表。表格如下:

BRANDS
BrandID // pk
BrandName

MODELS
ModelID // pk
BrandID // fk
ModelName

每个品牌都有零到多个与之相关的品牌。每个型号只能与一个品牌相关联。

我的输出应该是这样的:

Brand             # of Models
Goodyear               5
Chevy                  19
Toyota                 7  

我用来获取模型的查询如下所示:

SELECT   BrandID, BrandName
FROM     Brands
ORDER BY BrandName

我的计数查询如下所示:

SELECT COUNT(BrandID) AS TotalBrands
FROM Brands
WHERE SiteID = ?

我还需要从其他表格中查看其他一些内容。

您能开始介绍如何计算MODELS表中的项目吗?

感谢!!!

+++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++ ANSER

我用你所有的答案作为提示来帮助我得到我需要的东西。这是真正的查询。

        SELECT      S.SiteID,
                    S.SiteName,
                    COUNT(BrandID) AS TotalBrands
        FROM        Sites S
                    LEFT JOIN Brands B
                        ON S.SiteID = B.SiteID
        GROUP BY    S.SiteID, S.SiteName

3 个答案:

答案 0 :(得分:0)

这样的事情:

SELECT BrandID, COUNT(ModelID)
FROM BRANDS JOIN MODELS USING (BrandID)
GROUP BY BrandID

这将包括0型号的品牌。如果你也想要它们,你需要LEFT JOIN。

(Oracle语法,您可能需要使用ON而不是USING用于其他数据库)

答案 1 :(得分:0)

SELECT Brands.BrandID, COUNT(*)
FROM Brands INNER JOIN Models ON Brands.BrandID=Models.BrandID
GROUP BY Brands.BrandID

答案 2 :(得分:0)

SELECT B.BrandName AS 'Brand',
  ( SELECT COUNT(*) FROM Models AS M WHERE M.BrandID = B.BrandID ) as '# Of Models'
  FROM Brands AS B
  ORDER BY B.BrandName

这将包括零模型的品牌。您可以在WHERE子句中过滤掉它们:

WHERE exists ( SELECT 42 FROM Models WHERE BrandID = B.BrandID )