选择所有购买了 ID 为“CENTC”的客户已购买的所有产品的 CustomerNames
Posted
技术标签:
【中文标题】选择所有购买了 ID 为“CENTC”的客户已购买的所有产品的 CustomerNames【英文标题】:Select all CustomerNames that have bought all the products that have been bought by the Customer with the id 'CENTC' 【发布时间】: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'
但这是一次性解决方案,所以我不满意。
【问题讨论】:
【参考方案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;
【讨论】:
以上是关于选择所有购买了 ID 为“CENTC”的客户已购买的所有产品的 CustomerNames的主要内容,如果未能解决你的问题,请参考以下文章