How to select similar sets in SQL

后端 未结 8 1739
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 15:38

I have the following tables:

Order
----
ID (pk)

OrderItem
----
OrderID (fk -> Order.ID)
ItemID (fk -> Item.ID)
Quantity

Item
----
ID (pk)
         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 16:02

    The approach that I would take would be to first of all find all orderitems that are 85% similar to the orderitems for the selected order, then count the number of these orderitems for each order and check whether the number of items is 85% similar to the selected order, using the following query:

    DECLARE @OrderId int = 2
    SET @OrderId = 6
    
    /*
    Retrieve orderitems that match 85% with required @orderId
    */
    ;WITH SelectedOrderItemCount
    AS
    (
        SELECT COUNT(*) * 0.85 AS LowerBoundary, COUNT(*) * 1.15 AS UpperBoundary
        FROM OrderItem
        WHERE OrderId = @OrderId
    )
    SELECT OtherOrders.OrderId, COUNT(*) as NumberOfOrderItems
    FROM OrderItem SpecificOrder
    INNER JOIN OrderItem OtherOrders
        ON OtherOrders.ItemId = SpecificOrder.ItemId
    WHERE SpecificOrder.OrderId = @OrderId AND
          OtherOrders.OrderId <> @OrderId AND
        OtherOrders.Quantity BETWEEN SpecificOrder.Quantity * 0.85 AND SpecificOrder.Quantity * 1.15
    GROUP BY OtherOrders.OrderId
    HAVING COUNT(*) BETWEEN (SELECT LowerBoundary FROM SelectedOrderItemCount) 
                        AND (SELECT UpperBoundary FROM SelectedOrderItemCount)
    

    Full SQLFiddle demo here

提交回复
热议问题