Finding customers with identical orders

前端 未结 3 1373
[愿得一人]
[愿得一人] 2021-01-03 11:24

I need to find customers who have made identical orders. (Using T-SQL)

Order

OrderID Customerer  
1   2   
2   5   
3   6            


        
3条回答
  •  灰色年华
    2021-01-03 11:52

    Here's the most simple approach.

    -- sample table
    create table x
        (
             LineId int identity(1, 1)
            ,InvoiceFk int
            ,ProductFk int
            ,Quantity int
        )
    
    -- sample data
    insert into x 
    (InvoiceFk, ProductFk, Quantity) values
         (11, 1, 1)
        ,(11, 2, 1)
        ,(11, 3, 1)
        ,(12, 1, 2)
        ,(12, 2, 2)
        ,(12, 3, 2)
        ,(13, 1, 3)
        ,(13, 2, 3)
        ,(13, 3, 3)
    
    -- your order, probably from a parameter
    declare @order table
        (
             InvoiceFk int
            ,ProductFk int
            ,Quantity int
        )
    insert into @order
    (InvoiceFk, ProductFk, Quantity) values
         (14, 1, 1) -- duplicate invoice 11
        ,(14, 2, 1)
        ,(14, 3, 1)
    
    -- your order unique checksum
    declare @orderCheck int
    select @orderCheck = checksum_agg(checksum(ProductFk, Quantity))
    from @order
    
    -- test your order in existing data
    declare @match int
    select @match = 
        (
            select TOP 1 InvoiceFk from
            (
                select
                     InvoiceFk
                    ,checksum_agg(Col1) as Col2
                from
                    (
                    select 
                         InvoiceFk
                        ,checksum(productfk, quantity) as Col1
                    from x
                    ) as T1
                group by
                    InvoiceFk
            ) as T2
            where 
                T2.Col2 = @orderCheck
        )
    
    
    -- evaluate if your order is unique or not
    if (@match is not null)
    begin
        print 'Identical to invoice: ' + Str(@match);
    end
    else
    begin
        print 'Order is unique';
    end
    
    -- clean up sample table
    drop table x    
    

    Best of luck!

提交回复
热议问题