您需要選擇兩個不同的訂單,其中有相同產品的詳細信息。 (「選擇與同一產品有兩個不同訂單的所有客戶」)
Select
ContactName,
o1.OrderID,
o2.OrderID,
od1.ProductID
From
Customers
inner join Orders o1 on Customers.CustomerID = o1.CustomerID
join [Order Details] od1 on od.OrderID = o1.OrderID;
inner join Orders o2 on Customers.CustomerID = o2.CustomerID
join [Order Details] od2 on od.OrderID = o2.OrderID;
where
o1.orderid <> o2.orderid
and od1.productid = od2.productid
或使用子查詢。 (「選擇具有與同一客戶另一訂單中的同一產品的產品細節的所有客戶」);
Select
ContactName,
o1.OrderID,
od1.ProductID
From
Customers
inner join Orders o1 on Customers.CustomerID = o1.CustomerID
join [Order Details] od1 on od.OrderID = o1.OrderID;
where
od1.productid IN
(SELECT od2.productid
FROM
Orders o2 on Customers.CustomerID = o2.CustomerID
join [Order Details] od2 on od.OrderID = o2.OrderID
where
o1.orderid <> o2.orderid)
或使用group by。那麼你可以數它們。您可以彙總不同的值,例如訂購的總金額或支付的總獎金。
Select
ContactName,
od1.ProductID
count(*) as "number of repeated orders details",
count(distinct o1.orderid) as "number of different orders"
From
Customers
inner join Orders o1 on Customers.CustomerID = o1.CustomerID
inner join [Order Details] od1 on od.OrderID = o1.OrderID;
group by
ContactName,
od1.productId
having
count(distinct o1.orderid) > 1