我有一个问题,我不知道如何解决..这是代码和想要的结果
if object_id('tempdb..#A') IS NOT NULL drop table #A
create table #A (ID int, Value decimal(6,2), value2 decimal(6,2), Result decimal(6,2))
insert into #A (ID, Value, value2, Result)
values
(1, 10, 25, null),
(1, 10, 25, null),
(1, 10, 25, null),
(2, 10, 5, null),
(2, 10, 5, null),
select * from #A
所以,我想将值从" value2"中取出,如果有剩余,只是将其更新为0 ,对于下一行,我会采取那些"留下" 并使用它们带走下一个值
我想得到这样的结果......
ID Value value2 Result
1 10 25 0
----------------------------
1 10 25 0
----------------------------
1 10 25 5
----------------------------
2 10 5 5
----------------------------
2 10 5 10
因此,您可以看到ID 1 ...它将是:
10 - 25 = 0
10 - 15 = 0
10 - 5 = 5
我希望你明白我在这里要做的事情......如果我能解释更多,请告诉我......
答案 0 :(得分:2)
您似乎想要差异的累积总和,不允许负值。大多数数据库都支持窗口函数,其中包括累积总和:
我将假设id
确实指定了排序。您需要一些用于此目的的列,因为SQL表表示无序集并且没有排序。
但是,这样的事情应该有效:
select a.*,
sum(case when value2 >= value then 0 else value - value2 end) over
(order by id) as result -- or whatever the column is that specifies the ordering
from #A a;
答案 1 :(得分:0)
在戈登的帮助下,并使用了他的一些想法...我做了一些事情,此刻似乎有效,但还需要更多的测试
if object_id('tempdb..#testDataWithRunningTotal') IS NOT NULL drop table #testDataWithRunningTotal
select id, value, value2, cast(null as float) as Result
into #testDataWithRunningTotal
from #A order by id;
declare @runningTotal float = 0, @previousParentId int = null;
update #testDataWithRunningTotal
set
@runningTotal = Result = case when @previousParentId <> id
then value2 - value
else
case when ISNULL(@runningTotal,0) < 0 then value * (-1)
when value2 - value < 0 and ISNULL(@runningTotal,0) = 0 then value2
when value2 - value > 0 and ISNULL(@runningTotal,0) = 0 then value2 - value
else
case when @runningTotal - value < 0 and ISNULL(@runningTotal,0) = 0 then value
else @runningTotal - value
end
end
end,
@previousParentId = id
from #testDataWithRunningTotal
update tst
set Result = case when Result > 0
then 0
else Result * -1
end
from #testDataWithRunningTotal tst
select * from #testDataWithRunningTotal
所以,我保持@runningTotal运行更新,并允许它低于0 ...一旦它变得小于0,这意味着值的SUM大于Value2的SUM ...所以我记录在那里,在这个计算结束时我会更新。