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

本文介绍了一个SQL实现的问题,即从一组整数中找出三个数,使这三个数之和的绝对值达到最小,并给出了具体的SQL代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/*
描述:获取一组数据中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












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值