您是正确的,我之前的答案缺少一个术语。我今天在集群上花了一些时间,并编写了一个测试用例。下面是修改后的 SQL 和设置语句。它需要一个新术语,它是一个窗口函数,因为它们不能嵌套另一个选择层。我希望这个示例有所帮助,而且我知道解决非递归数据库上的递归问题可能很困难。
drop table if exists package_volume;
create table package_volume (
A timestamp encode zstd,
B int encode zstd,
C int encode zstd);
insert into package_volume values
('2020-06-26 13:00', 0, 0),
('2020-06-26 14:00', 3500, 0),
('2020-06-26 15:00', 3200, 0),
('2020-06-26 16:00', 6500, 0),
('2020-06-26 17:00', 5200, 50000),
('2020-06-26 18:00', 51000, 50000),
('2020-06-26 19:00', 120000, 50000),
('2020-06-26 20:00', 30000, 50000),
('2020-06-26 21:00', 40000, 50000),
('2020-06-26 22:00', 15000, 50000),
('2020-06-26 23:00', 5500, 50000),
('2020-06-27 00:00', 0, 0);
commit;
select A, B, C,
run_tot_pack - run_tot_capacity + sum(unrealized_capacity) over (order by A rows unbounded preceding) as available_volume
from (
select A, B, C, run_tot_pack, run_tot_capacity,
decode(unrealized_capacity - max(unrealized_capacity) over (order by A rows between unbounded preceding and 1 preceding) < 0, true, 0,
unrealized_capacity - max(unrealized_capacity) over (order by A rows between unbounded preceding and 1 preceding)) as unrealized_capacity
from (
select A, B, C,
sum(B) over (order by A rows unbounded preceding) as run_tot_pack,
sum(C) over (order by A rows unbounded preceding) as run_tot_capacity,
decode(run_tot_pack - run_tot_capacity < 0, true, run_tot_capacity - run_tot_pack, 0) as unrealized_capacity
from package_volume
)
)
order by A;