假设我有2个表T1T2如下

T1

bag_id bag_type capacity
------|--------|--------
  1       A       500
  2       A       300
  3       A       100
  4       B       200
  5       B       100


T2

item_type item_amount
---------|-----------
   A         850
   B         300


T1中的每个记录代表一个袋子及其容量,这里我有5个袋子。我想编写一个将表T2中的项目分配到具有相同类型的每个包中的SQL,即结果应如下所示

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


因此,我发现了某种聚合函数,我们称其为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


我当前的解决方案是使用临时表和PL / SQL循环进行计算,但是我希望我可以使用一个简单的SQL来实现。

最佳答案

您正在寻找累计金额。像这样:

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;

09-10 10:05
查看更多