2 个关于罗斯文的问题 SQL

2 Questions on Northwind SQL

我有 2 个关于 Northwind SQL 服务器示例数据库的问题,我不知道如何解决

  1. 为至少拥有三种不同产品但从未在同一类别中使用这两种产品的所有客户显示 CustomerID

    我为这个问题试过的代码:

    SELECT 
        CustomerID, p.ProductID,ProductName, CategoryID
    FROM 
        (Orders o 
    JOIN 
        [Order Details] od ON o.OrderID = od.OrderID)
    JOIN
        Products p ON od.ProductID = p.ProductID
    
  2. 为有所有类别订单的客户显示 CustomerID

我已经被这些问题困扰了几个小时,请大家帮忙!

这是 link 用于 Northwind 示例数据库:https://northwinddatabase.codeplex.com/

对于#2,你可以使用这样的东西:

SELECT
    c.CustomerID, COUNT(DISTINCT p.CategoryID)
FROM 
    dbo.Customers c
INNER JOIN 
    dbo.Orders o ON o.CustomerID = c.CustomerID
INNER JOIN 
    dbo.[Order Details] od ON od.OrderID = o.OrderID
INNER JOIN 
    dbo.Products p ON p.ProductID = od.ProductID
GROUP BY
    c.CustomerID
HAVING
    COUNT(DISTINCT p.CategoryID) = (SELECT COUNT(*) FROM dbo.Categories)

这适用于问题 #1:

SELECT c.CustomerID, 
    od.productid, 
    p.ProductName, 
    COUNT(od.productid), 
    ct.Category
FROM [Order Details] od

INNER JOIN [dbo].[Products] p on od.ProductID    = p.ProductID
INNER JOIN [dbo].[Categories] ct on p.CategoryID = c.CategoryID
INNER JOIN [dbo].[Orders] o on od.OrderID        = o.OrderID
INNER JOIN [dbo].[Customers] c on o.CustomerID   = c.CustomerID

GROUP BY od.productid,
         ct.CategoryID,
         p.ProductName,
         c.CustomerID
HAVING COUNT(od.productid) > 3
ORDER BY COUNT(od.productid) desc
;