2017-04-13 79 views
-1

我有一个表值函数,它返回与给定总和相匹配的行集合,它对正值有效,但对负值无效。SQL子集合总和为负值

有人可以修改这个功能与正反两方面的价值(价格领域)工作

功能需要一个表的十进制值,然后返回匹配的参数给定的总和的行的第一组合:

例如,如果@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 @[email protected]+1 set @s=0 
while 0=0 
begin --2 
while @n>1 
begin --3 
set @[email protected] 
if @s+(select price from @t where [email protected])<[email protected] 
and @s+(select sum(price) from @t where n<[email protected])>[email protected] 
begin --4 
set @[email protected]+(select price from @t where [email protected]) 
insert into @tt select n, id, price from @t where [email protected] 
if @[email protected] return ; 
end --4 
end --3 
set @n=(select min(n) from @tt) 
set @[email protected](select price from @tt where [email protected]) 
delete from @tt where [email protected] 
if @s=0 and (select sum(price) from @t where n<@n)<@sum break 
end --2 
end --1 

return 
END 
+0

请通过告诉我们该功能与应该做什么来节省时间。以及一些输出示例。 – Stephen

+0

'-5 + 5 + 5 + 4 = 9'这是不正确的?你希望你的负面金额被视为积极的? – Stephen

+0

是的,这是正确的,但该功能不适用于该示例。 – oussama

回答

-1

将绝对功能ABS(价格)用于治疗阴性为阳性

+0

我不想把native否定为正值 – oussama