-1

我有 2 个关于NorthwindSQL Server 示例数据库的问题,我不知道如何解决

  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给拥有所有类别订单的客户。

我一直在这些问题上停留了几个小时,请大家帮忙!

这是Northwind示例数据库的链接:https ://northwinddatabase.codeplex.com/

4

2 回答 2

1

对于#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)
于 2015-12-25T11:09:22.133 回答
-2

这适用于问题 #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
;
于 2016-08-12T10:59:44.417 回答