Getting the lowest possible sum from numbers' difference

后端 未结 10 1279
滥情空心
滥情空心 2020-12-23 22:19

I have to find the lowest possible sum from numbers\' difference.

Let\'s say I have 4 numbers. 1515, 1520, 1500 and 1535. The lowest sum of difference is 30, becaus

10条回答
  •  时光说笑
    2020-12-23 22:56

    I know you said you did not need code but it is the best way for me to describe a set based solution. The solution runs under SQL Server 2008. Included in the code is the data for the two examples you give. The sql solution could be done with a single self joining table but I find it easier to explain when there are multiple tables.

        --table 1 holds the values
    
    declare @Table1 table (T1_Val int)
    Insert @Table1 
    --this data is test 1
    --Select (1515) Union ALL
    --Select (1520) Union ALL
    --Select (1500) Union ALL
    --Select (1535) 
    
    --this data is test 2
    Select (1731) Union ALL
    Select (1572) Union ALL
    Select (2041) Union ALL
    Select (1561) Union ALL
    Select (1682) Union ALL
    Select (1572) Union ALL
    Select (1609) Union ALL
    Select (1731) 
    --Select * from @Table1
    
    --table 2 holds the sorted numbered list
    Declare @Table2 table (T2_id int identity(1,1), T1_Val int)
    Insert @Table2 Select T1_Val from @Table1 order by T1_Val
    
    --table 3 will hold the sorted pairs
    Declare @Table3 table (T3_id int identity(1,1), T21_id int, T21_Val int, T22_id int, T22_val int)
    Insert @Table3
    Select T2_1.T2_id, T2_1.T1_Val,T2_2.T2_id, T2_2.T1_Val from @Table2 AS T2_1
    LEFT Outer join @Table2 AS T2_2 on T2_1.T2_id = T2_2.T2_id +1
    
    --select * from @Table3
    --remove odd numbered rows
    delete from @Table3 where T3_id % 2 > 0 
    
    --select * from @Table3
    --show the diff values
    --select *, ABS(T21_Val - T22_val) from @Table3
    --show the diff values in order
    --select *, ABS(T21_Val - T22_val) from @Table3 order by ABS(T21_Val - T22_val)
    --display the two lowest
    select TOP 2 CAST(T22_val as varchar(24)) + ' and ' + CAST(T21_val as varchar(24)) as 'The minimum difference pairs are'
    , ABS(T21_Val - T22_val) as 'Difference'
    from @Table3
    ORDER by ABS(T21_Val - T22_val) 
    

提交回复
热议问题