各位大大好:
    不知道小弟说不说的明白!
    现在有一个表,里面有很多条记录,表的一个字段是表示金额的(例如叫money),现在用户需要的功能是给定一个数值,例如1000,要在表里找出字段总和(sum(money))最接近1000的那些记录,请问这个sql语句怎么写呢?

解决方案 »

  1.   

    select col1,min(col) from 
    (select col1,sum(money)-1000 col2 from [table] group by col1)t
    group by col1
      

  2.   

    select col1,min(col2) col2 from 
    (select col1,sum(money)-1000 col2 from [table] group by col1)t
    group by col1
      

  3.   

    总之就是选出分组中,sum(money)-1000 这个差值最小的那条记录
      

  4.   

    这样问,会不会好一点。
    例如1000,要在表里找出字段总和(sum(money))最接近1000的(大小在-500至500之间)那些记录,请问这个sql语句怎么写呢?
    select [名字],sum(money) from [表1] group by [名字]  having sum(money)>=-500 and sum(money)<=500
      

  5.   

    我之前那个写错了,而且没考虑差值为负数的情况,用这种思路试试看:select top 1 * from 
    (select col1,ABS(sum(col2)-1000) col2 from [talbename] group by col1) t
    order by col2