SQL子集求和值

时间:2017-04-13 08:52:21

标签: sql sql-server-2008-r2 subset-sum

我有一个表值函数,它返回与给定总和匹配的行集,它对正值有效,但对负值不正常。

有人可以修改此功能以使用正值和负值(价格字段)

该函数采用带有十进制值的表,然后返回与参数中给定总和匹配的第一行组合:

例如,如果@psum = 9和下面的给定表:

n   id  price
1   1   4.00
2   2   4.00
3   3   5.00
4   4   6.00
5   5   8.00

输出结果是:

select * from SubsetSum2(9)

n   id  price
3   3   5.00
2   2   4.00

alter FUNCTION [dbo].[SubsetSum2](@psum int )  
RETURNS  @tt table  (n int,id int, price numeric(20,2))
AS  
BEGIN

declare @t table  (n int IDENTITY(1,1), id int,  price numeric(20,2))
insert into @t -- note asc order of book prices

select  1, 4 union all
select  2, 4 union all
select  3, 5 union all
select  4, 6 union all
select  5, 8 

declare @rows int, @p numeric(20,2), @sum numeric(20,2) set @sum= 9
delete from @t where price>@sum
set @p=(select sum(price) from @t)

if @p>= @sum
begin --1
set @rows=(select max(n) from @t)
declare @n int, @s numeric(20,2)
set @n=@rows+1 set @s=0
while 0=0
begin --2
while @n>1
begin --3
set @n=@n-1
if @s+(select price from @t where n=@n)<=@sum
and @s+(select sum(price) from @t where n<=@n)>=@sum
begin --4
set @s=@s+(select price from @t where n=@n)
insert into @tt select n, id, price from @t where n=@n
if @s=@sum return ; 
end --4
end  --3
set @n=(select min(n) from @tt)
set @s=@s-(select price from @tt where n=@n)
delete from @tt where n=@n
if @s=0 and (select sum(price) from @t where n<@n)<@sum break
end --2
end --1

return
END

1 个答案:

答案 0 :(得分:-1)

使用绝对函数ABS(Price)将负数视为正数