问题点是,表中一个字段有1-5不等的数字,记录条数若干。
我想将这些数据分组,条件就是把其中能相加等于9的记录分到一组。当然这个sql的结果应该不是唯一的,
但我只是想解决这个算法。
如果实现上不太好弄的话,也可以只取一组相加等于9的记录,如果没有,返回相加最接近的一组也可以另外,这个算法的学名应该怎么叫,如果不能拿SQL做到的话,我想去查查相关其它语言能如何解决
恳请高手指点迷津~~在下先行谢过了。ID      val
-------------------
1        4
2        2
3        5
4        1
5        3
6        4
7        3

解决方案 »

  1.   


    declare @T table (ID int,val int)
    insert into @T
    select 1,4 union all
    select 2,2 union all
    select 3,5 union all
    select 4,1 union all
    select 5,3 union all
    select 6,4 union all
    select 7,3select top 4 * from @T a ,@T b
    where a.id>b.id order by abs(a.val+b.val-9)/*
    --之取2个数的时候  
    --最接近的是5和4 4和5
    --其次是 3和5 4和4 
    ID          val         ID          val
    ----------- ----------- ----------- -----------
    3           5           1           4
    6           4           3           5
    6           4           1           4
    5           3           3           5
    */
      

  2.   

    这个组合有C71+C72+C73+C74+C75+C76+C77种情况,需要都考虑到,然后order by abs(sum(组合)-9)
      

  3.   


    declare @T table (ID int,val int)
    insert into @T
    select 1,4 union all
    select 2,2 union all
    select 3,5 union all
    select 4,1 union all
    select 5,3 union all
    select 6,4 union all
    select 7,3select top 15 * from 
    (
    select a.val as c1,b.val as c2,0 as c3,0 as c4 from @T a ,@T b where a.id>b.id
    union all
    select a.val,b.val,c.val,0 from @T a ,@T b, @T c where a.id>b.id and b.id>c.id
    union all
    select a.val,b.val,c.val,d.val from @T a ,@T b, @T c,@T d 
    where a.id>b.id and b.id>c.id and c.id>d.id
    ) a
    order by abs(c1+c2+c3+c4-9)/*
    c1          c2          c3          c4
    ----------- ----------- ----------- -----------
    5           4           0           0
    4           5           0           0
    3           2           4           0
    3           1           5           0
    4           1           4           0
    4           3           2           0
    3           2           4           0
    3           1           5           0
    3           4           2           0
    3           3           1           2
    4           4           0           0
    3           5           0           0
    3           5           0           0
    1           5           4           0
    1           5           2           0
    */