【问题标题】:Select all CustomerNames that have bought all the products that have been bought by the Customer with the id 'CENTC'选择所有购买了 ID 为“CENTC”的客户已购买的所有产品的 CustomerNames
【发布时间】:2021-12-05 18:52:25
【问题描述】:

我正在使用 Northwind 数据库

目前我已经尝试过

这是我选择客户订单的地方

select od.ProductID from Customers c JOIN
Orders o on c.CustomerID=o.CustomerID
JOIN [Order Details] od on o.OrderID=od.OrderID
where c.CustomerID='CENTC'

这是我的解决方案

select distinct c.CompanyName, sum(od.ProductID) as suma from Customers c JOIN
Orders o on c.CustomerID=o.CustomerID
JOIN [Order Details] od on o.OrderID=od.OrderID
where od.ProductID = '40' or od.ProductID = '11'
group by c.CompanyName
having sum(od.ProductID)='51'

但这是一次性解决方案,所以我不满意。

【问题讨论】:

    标签: sql-server join northwind


    【解决方案1】:

    您可以为此使用IN 子查询

    SELECT
      c.CompanyName,
      c.ContactName,
      SUM(od.quantity) AS quantity
    FROM Customers c
    JOIN Orders o on c.CustomerID = o.CustomerID
    JOIN OrderDetails od on o.OrderID = od.OrderID
    WHERE od.ProductID IN (
        SELECT od2.ProductID
        FROM Orders o2
        JOIN OrderDetails od2 on o2.OrderID = od2.OrderID
        WHERE o2.CustomerID = 'CENTC'
    )
    GROUP BY
      c.CustomerID,
      c.CompanyName,
      c.ContactName;
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多