2010-11-02 48 views
0

好的,我試圖鏈接三個不同的表(客戶,訂單和訂單詳細信息),以試圖找出哪些客戶訂購了兩次相同的項目。我很難過。下面是我想出迄今:SQL Server - 鏈接表,重複項目

Select ContactName, Orders.OrderID, ProductID From Customers 
inner join Orders on Customers.CustomerID = Orders.CustomerID 
join [Order Details] on [Order Details].OrderID = Orders.OrderID; 

我想它會是最容易找到具有相關聯繫人姓名,但不同的Orders.OrderID ProductIDs ......這是我什麼遇到麻煩。任何幫助將非常感激。

回答

0

您需要選擇兩個不同的訂單,其中有相同產品的詳細信息。 (「選擇與同一產品有兩個不同訂單的所有客戶」)

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