Select all CustomerNames that have bought id 为 'CENTC' 的客户购买的所有产品

Select all CustomerNames that have bought all the products that have been bought by the Customer with the id 'CENTC'

我正在使用 Northwind 数据库

目前我已经试过了

这是我select客户订单的地方

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'

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

您可以为此使用 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;