在 SQL 服务器中将 Count() 与自连接一起使用

Use Count() with self join in SQL Server

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

Which suppliers offer two products in the same category? Show company name, category and the both product names

我的代码:

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 进行过滤,但失败了。 我会感谢一些帮助,这让我回到正确的道路上。

您可以使用如下查询获取恰好包含两种产品的 suppliers/categories 列表:

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

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

基于 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
            )