如何选择记录数,然后用外键对它们进行分组?

时间:2013-02-20 02:19:12

标签: sql select count

我有两张桌子:产品和供应商。 SupplierID是产品表中的外键。我需要从供应商表中创建一个包含country,supplierID,公司名称的表,然后我需要拥有每个供应商拥有的产品数量。我尝试了以下查询:

SELECT DISTINCT s.country, 
                s.supplierid, 
                s.companyname, 
                (SELECT Count(DISTINCT productid) AS 
                        "Number of Products Supplied" 
                 FROM   products 
                        INNER JOIN suppliers 
                                ON p.supplierid = s.supplierid) AS 
                "Number of products Supplied" 
FROM   suppliers s, 
       products p 
WHERE  ( s.country = 'usa' 
          OR s.country = 'uk' ) 
       AND s.supplierid = p.supplierid 

但我得到的是产品总数,而不是每个供应商提供的产品数量。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

SELECT s.country, s.supplierid, s.companycame, Count(*) AS Number_of_Products_Supplied
FROM suppliers s
 JOIN products p ON s.supplierid=p.supplierid
WHERE s.country IN ('usa', 'uk')
GROUP BY s.country, s.supplierid, s.companycame

如果我理解你的问题,我认为应该做你想做的事。