您的位置:首页 > 数据库

用sql求一组数据中的3个和最小的数值

2008-04-24 20:55 453 查看



/**//*


描述:获取一组数据中3个和的绝对值最小的数据


在测试中,输入了有重复值的数据,有重复时,只当作一个数字


原题:N个int数,求其中三个数,使得其和的绝对值最小,如{-3,9,-5,90}的三个数是{-3,9,-5},要求分析时间和空间复杂度。


*/


set nocount on


if exists(select 1 from sys.tables where name = 't')


drop table t




create table t (id int,hi int default 0 )


insert into t(id) select -10


insert into t(id) select -11


insert into t(id) select -9


insert into t(id) select 6


insert into t(id) select 10


insert into t(id) select -10


insert into t(id) select 6


insert into t(id) select -6


insert into t(id) select -10


insert into t(id) select 0


insert into t(id) select -2


insert into t(id) select 15


insert into t(id) select 25


insert into t(id) select -20


insert into t(id) select -5


--输出测试数据


select * from t


order by id




declare @id int,@op_id int,@min_id int


declare cur cursor for select id from t where id>0




declare @temp table(id1 int ,id2 int,id3 int ,hi int)




open cur


fetch next from cur into @id


while (@@fetch_status=0)


begin


select top 1 @op_id =min(abs(@id+id)) from t


select top 1 @min_id=min(abs(@op_id+id)) from t




insert into @temp select @id, @op_id-@id, @min_id-@op_id,@min_id


update t


set hi=@min_id


where id=@id


fetch next from cur into @id


end




--输出需要测试的数据


select * from @temp where hi=(select min(hi) from @temp)


close cur


deallocate cur

























内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐