我有2个关于Northwind
SQL Server示例数据库的问题,我不知道如何解决
为所有拥有至少三种不同产品但从不在同一类别中使用这两种产品的客户展示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
为拥有所有类别订单的客户显示CustomerID
。
我已经被困在这些问题上好几个小时了,请帮帮我们!
这是Northwind
示例数据库的链接:https://northwinddatabase.codeplex.com/
答案 0 :(得分: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)
答案 1 :(得分:-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
;