【问题标题】:SQL subset sum negative valuesSQL 子集总和负值
【发布时间】:2017-04-13 08:52:21
【问题描述】:

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

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

该函数获取一个包含十进制值的表,然后返回与参数中给定总和匹配的第一个行组合:

例如,如果@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

【问题讨论】:

  • 请告诉我们函数的作用与它应该做什么来节省我们的时间。带有一些输出示例。
  • -5+5+5+4 = 9 这不正确吗?您希望您的负数被视为正数吗?
  • 是的,这是正确的,但该函数不适用于该示例。
  • 给定 select 2, -5 union all 而不是 select 2, 4 union all 你期望什么输出? “组合”是否应该始终按顺序排列(下一行)?
  • 在这种情况下,预期结果是:n id price | 3 3 5.00 | 1 1 4.00 不分组合顺序

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


【解决方案1】:

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

【讨论】:

  • 我不想将消极视为积极
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多