寻找匹配集

时间:2014-11-21 12:04:43

标签: sql-server tsql

考虑这些表格

create table orders
(orderid int primary key)

create table orderlines
(orderid int foreign key (orderid) references orders,
 product nvarchar(max))

使用这样的数据

 insert into orders values (1)
 insert into orders values (2)
 insert into orders values (3)
 insert into orders values (4)
 insert into orders values (5)
 insert into orders values (6)


 insert into orderlines values (3, 'p1')
 insert into orderlines values (3, 'p2')
 insert into orderlines values (4, 'p1')
 insert into orderlines values (4, 'p2')
 insert into orderlines values (5, 'p1')
 insert into orderlines values (5, 'p3')
 insert into orderlines values (6, 'p1')

什么查询会为我提供在订单上具有完全相同产品的订单对?

预期输出

orderid     orderid
----------- -----------
1           2
3           4

因为订单1和2都没有订单 订单3和4具有完全相同的产品集(p1,p2)

需要考虑的事项:

  • 仅选择每一对(通过保留每个对的左orderid< right orderid来实现)
  • 还包括完全没有订单行的对(订单1和2)
  • 仅包括订单中具有完全相同产品的订单(订单3和4)

选择的武器:t-sql / sqlserver 2008

1 个答案:

答案 0 :(得分:3)

通过询问问题,我现在通过查看相关问题找到答案: Finding customers with identical orders

SELECT  O1.OrderID ,
        O2.OrderID 
FROM    [Orders] O1
        JOIN [Orders] O2 ON O1.OrderID < O2.OrderID
WHERE   NOT EXISTS ( SELECT productid 
                     FROM   OrderLines
                     WHERE  O1.OrderID = OrderLines.OrderID
                     EXCEPT
                     SELECT productid
                     FROM   OrderLines
                     WHERE  O2.OrderID = OrderLines.OrderID )
        AND NOT EXISTS ( SELECT productid 
                     FROM   OrderLines
                     WHERE  O2.OrderID = OrderLines.OrderID
                     EXCEPT
                     SELECT productid
                     FROM   OrderLines
                     WHERE  O1.OrderID = OrderLines.OrderID )