查找具有完全相同的子行集的Sql父行

时间:2014-11-26 11:38:01

标签: sql sql-server left-join

我有一个带有订单的MS SQL数据库。有两个表矿工和订单。 我想获得具有相同订单的所有订单:这意味着显示具有完全相同产品和数量的订单。

创建表格和数据:

CREATE TABLE [dbo].[orders](
    [orderid] [int] NULL
) ON [PRIMARY]

GO

INSERT INTO orders values(1)
INSERT INTO orders values(2)
INSERT INTO orders values(3)
INSERT INTO orders values(4)

CREATE TABLE [dbo].[orderrows](
    [orderid] [int] NULL,
    [LineNum] [int] NULL,
    [Quantity] [decimal](18, 6) NULL,
    [ItemCode] [nvarchar](20) NULL
) ON [PRIMARY]

GO

INSERT INTO orderrows values(1,0,11.0,'Item1')
INSERT INTO orderrows values(1,1,12.0,'Item2')
INSERT INTO orderrows values(1,2,13.0,'Item3')
INSERT INTO orderrows values(1,3,14.0,'Item4')
INSERT INTO orderrows values(2,0,11.0,'Item1')
INSERT INTO orderrows values(2,1,12.0,'Item2')
INSERT INTO orderrows values(2,2,13.0,'Item3')
INSERT INTO orderrows values(2,3,14.0,'Item4')
INSERT INTO orderrows values(3,0,11.0,'Item1')
INSERT INTO orderrows values(3,1,12.0,'Item2')
INSERT INTO orderrows values(4,0,15.0,'Item5')
INSERT INTO orderrows values(4,1,16.0,'Item6')

我已创建此查询:

select t1.orderid, t1.Itemcode, t1.quantity, t1.LineNum, t2.orderid, t2.Itemcode 
FROM orderrows t1
    LEFT OUTER JOIN orderrows t2 ON t1.itemcode = t2.ItemCode and t1.quantity = t2.Quantity and t2.LineNum = t1.linenum
    where t1.orderid <> t2.orderid
    order by t1.orderid, t2.orderid

这给出了以下结果:

enter image description here

有没有人知道要摆脱划掉的行?这些订单不是完全匹配,但仅包含订单的子集。例如第5行和第6行显示订单3,但此订单仅包含item1和item2。

1 个答案:

答案 0 :(得分:3)

这是一种方法 - 构建orderid的所有组合,然后使用EXCEPT来消除不匹配的订单。我假设LineNum与'确切'比较无关。

-- Build up all combinations of orders
WITH orderPairs AS
(
    select o1.orderid as orderid1, o2.orderid as orderid2
    from orders o1
        cross join orders o2
    where 
        o1.orderid > o2.orderid -- prevent self matches, and duplicate checks
)
SELECT *
  FROM orderPairs op
  WHERE 
    NOT EXISTS
    -- All in O1 are in O2
    (SELECT ItemCode, Quantity 
      FROM orderrows orw1 
      WHERE orw1.orderid = op.orderid1 

      EXCEPT 

      SELECT ItemCode, Quantity 
      FROM orderrows orw2 
      WHERE orw2.orderid = op.orderid2)

    AND NOT EXISTS

    -- All in O2 are in O1
    (SELECT ItemCode, Quantity 
     FROM orderrows orw2 
      WHERE orw2.orderid = op.orderid2

      EXCEPT 

      SELECT ItemCode, Quantity 
      FROM orderrows orw1 
      WHERE orw1.orderid = op.orderid1 )

这不一定是最有效的方法(例如,早期行数可以避免逐行匹配)

SqlFiddle here,表示Order1Order2相同。