【问题标题】:Use Count() with self join in SQL Server在 SQL Server 中使用 Count() 和自联接
【发布时间】:2016-11-18 11:17:03
【问题描述】:

我正在使用北风数据库,我的练习是:

哪些供应商提供同一类别的两种产品?显示公司名称、类别和两个产品名称

我的代码:

SELECT DISTINCT 
    c.CategoryID, s.CompanyName, p1.ProductName, p2.ProductName
FROM 
    Suppliers s 
INNER JOIN 
    Products p1 ON s.SupplierID = p1.SupplierID
INNER JOIN 
    Products p2 ON p1.CategoryID = p2.CategoryID 
                AND p1.ProductID <> p2.ProductID
INNER JOIN 
    Categories c ON p2.CategoryID = c.CategoryID
GROUP BY 
    c.CategoryID,s.CompanyName, p1.ProductName, p2.ProductName`

如何使用 COUNT() 过滤它我尝试使用 HAVING 进行过滤,但失败了。 我会很感激一些帮助,这让我回到了正确的道路上。

【问题讨论】:

  • 请提供样本数据和您的预期结果
  • 您想要的输出格式是什么?您当前的查询不会为拥有 3 种产品的供应商返回合理的结果。产品必须在单独的列中,还是每个供应商只有两行?
  • 应该是供应商名称的一行,两个产品具有相同的类别id和类别id

标签: sql-server join count self


【解决方案1】:

基于 Gordon 的回答,下面的代码将获得您需要的所有数据。如果您绝对必须将两种产品放在同一行,则可以使用pivot

select s.CompanyName
        ,p.ProductName
from Suppliers s
    -- This join filters your Suppliers table to only those with two Products in the same Category
    inner join (select SupplierID
                        ,CategoryID
                from Products
                group by SupplierID
                        ,CategoryID
                having count(1) = 2
                ) pc
        on(s.SupplierID = pc.SupplierID)

    -- This join returns the two products in the Category returned in the join above.
    inner join Products p
        on(s.SupplierID = p.SupplierID
            and pc.CategoryID = p.CategoryID
            )

【讨论】:

【解决方案2】:

您可以使用这样的查询获得正好包含两种产品的供应商/类别列表:

select supplierId, categoryId
from products
group by supplierId, categoryId
having count(*) = 2;

然后,编写一个查询来显示供应商和产品名称,并使用上述内容过滤该查询的结果。您可以使用exists 或额外的join

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 2013-01-28
    • 2014-07-05
    • 2017-08-14
    • 2017-11-02
    相关资源
    最近更新 更多