Oracle聚合函数分配金额

asi*_*swt 8 sql oracle data-warehouse aggregate-functions oracle11g

假设我有2个表T1,T2如下所示

T1:

bag_id bag_type capacity
------|--------|--------
  1       A       500
  2       A       300
  3       A       100
  4       B       200
  5       B       100
Run Code Online (Sandbox Code Playgroud)

T2:

item_type item_amount
---------|-----------
   A         850
   B         300
Run Code Online (Sandbox Code Playgroud)

表中的每个记录T1代表一个包及其容量,这里我有5个包.我想编写一个SQL,将表中的项目分配T2到具有相同类型的每个包中,即结果应该是这样的

bag_id bag_type capacity allocated_amount
------|--------|--------|----------------
  1       A        500        500
  2       A        300        300
  3       A        100        50
  4       B        200        200
  5       B        100        100
Run Code Online (Sandbox Code Playgroud)

因此,我发现了一些聚合函数,我们称之为allocate()可以产生allocated_amount如上所述的列.我猜想,如果存在,它可能会像这样使用

select 
    t1.bag_id,
    t1.bag_type, 
    t1.capacity,
    allocate(t2.item_amount, t1.capacity) 
        over (partition by t1.bag_type order by t1.capacity desc) as allocatd_amount
from t1, t2
where t2.item_type = t1.bag_type
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是使用临时表和PL/SQL循环进行计算,但我希望我能用一个简单的SQL来完成.

Gor*_*off 4

您正在寻找累积总和。像这样的东西:

select t1.*,
       (case when cumecap <= t2.item_amount 
             then t1.capacity
             when cumecap - t1.capacity <= t2.item_amount
             then t2.item_amount - (cumecap - t1.capacity)
             else 0
        end) as allocated_capacity
from (select t1.*,
             sum(t1.capacity) over (partition by bag_type order by bag_id) as cumecap
      from t1
     ) t1 join
     t2
     on t1.bag_type = t2.item_type;
Run Code Online (Sandbox Code Playgroud)