Oracle aggregation function to allocate amount

后端 未结 3 1356
孤独总比滥情好
孤独总比滥情好 2021-02-15 16:29

Suppose I have 2 tables T1 and T2 as follows

T1:

bag_id bag_type capacity
------|--------|--------
  1       A             


        
3条回答
  •  情书的邮戳
    2021-02-15 17:28

    You are looking for a cumulative sum. Something like this:

    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;
    

提交回复
热议问题