SQL匹配来自2个表的数据

时间:2016-07-23 14:08:26

标签: sql sqlite

我有两张桌子。

'Order details'
OrderID | Quantity | UnitPrice | ProductID
  1002  |    19    |    17     |    824
  1002  |    5     |    15     |    285
  1003  |    7     |    17     |    824
  1003  |    7     |    15     |    285
  1003  |    7     |    11     |    205
  1004  |    12    |    11     |    205


'Orders'
OrderID | CustomerID
  1002  |   224
  1003  |   348
  1004  |   224

我需要找到与另一个CustomerID具有相同订单(ProductID)的CustomerID,例如ID号224.必须采取所有订单,我的意思是所有订单ID。 所以输出将是348,因为这个id在他的命令中具有绝对相同的产品。

3 个答案:

答案 0 :(得分:1)

如果您希望客户使用相同的产品:

where

CTE的目的只是为每个客户,产品和产品数量增加一行。外部查询计算两个客户之间的匹配数。匹配数量需要与产品数量相匹配。

这将返回完全匹配。第二个客户必须拥有完全相同的产品,不多也不少。

注意:这将返回原始客户(使用{{1}}子句轻松过滤掉)。

答案 1 :(得分:0)

在下面的草图中,我列出了与客户ID 224所做的某些订单完全相同的产品的所有订单

select distinct o2.OrderId
from    
    Orders o1, Orders o2
where 
    o1.CustomerId = 224
    and o1.OrderId <> o2.OrderId
    and not exists (
        select 1 
        from 
            "Orders details" od1 
            full outer join "Order details" od2 on 
                od1.OrderId = o1.OrderId 
                and od2.OrderId = o2.OrderId 
                and od1.ProductId = od2.ProductId
        where
            od1.OrderId is null or od2.OrderId is null
    )

其余的应该很容易。

如果您的DBMS不支持完全外连接,您可以将其拆分为两个左连接,如下所示:

select distinct o2.OrderId
from    
    Orders o1, Orders o2
where 
    o1.CustomerId = 224
    and o1.OrderId <> o2.OrderId
    and not exists (
        select 1 
        from 
            "Orders details" od1 
            left join "Order details" od2 on 
                od1.OrderId = o1.OrderId 
                and od2.OrderId = o2.OrderId 
                and od1.ProductId = od2.ProductId
        where
            od2.OrderId is null
    )
    and not exists (
        select 1 
        from 
            "Orders details" od1 
            left join "Order details" od2 on 
                od1.OrderId = o2.OrderId 
                and od2.OrderId = o1.OrderId 
                and od1.ProductId = od2.ProductId
        where
            od2.OrderId is null
    )

答案 2 :(得分:0)

with cte1 as 
(  select CustomerID, ProductID 
     from order 
     join detail
       on order.OrderID  = detail.OrderID )
, cte2 as 
(  select CustomerID, count(*) as cnt 
   from cte1 
   group by CustomerID
)
select cte2a.CustomerID, cte2b.CustomerID
  from cte2 as cte2a
  join cte2 as cte2b
    on cte2a.CustomerID < cte2a.CustomerID
   and cte2a.cnt< cte2a.cnt
  join cte1 as cte1a
    on cte1a.CustomerID = cte2a.CustomerID
  join cte1 as cte1b
    on cte1b.CustomerID = cte2b.CustomerID
   and cte1a.ProductID  = cte1b.ProductID 
 group by cte2a.CustomerID, cte2b.CustomerID, cte2a.cnt
 having count(*) = cte2a.cnt