SQL Server - 链接表,重复项

时间:2010-11-02 06:21:37

标签: sql

好吧,我正在尝试链接三个不同的表(客户,订单和订单明细),以确定哪些客户订购了两次相同的商品。我很难过。这是我到目前为止所提出的:

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的ProductID ...这就是我遇到的问题。任何帮助将非常感激。

1 个答案:

答案 0 :(得分: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