2017-04-13 74 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