Oracle aggregation function to allocate amount

后端 未结 3 1355
孤独总比滥情好
孤独总比滥情好 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:29

    assuming allocation in the descendent order of bag capacity

    with agg as ( 
    select bag.BAG_ID, bag.BAG_TYPE, bag.CAPACITY,
    SUM(bag.CAPACITY) over (partition by bag.bag_type order by bag.capacity DESC) agg_capacity,
    item_amount
    from bag, item
    where bag.bag_type = item.item_type
    )
    select 
        BAG_ID, BAG_TYPE, CAPACITY, 
        case when ITEM_AMOUNT >= AGG_CAPACITY then CAPACITY /* Full allocated */
        when ITEM_AMOUNT >= AGG_CAPACITY-CAPACITY then  ITEM_AMOUNT - (AGG_CAPACITY-CAPACITY) /* partly allocated */ 
        else 0 end /* not allocated */
        as allocated 
    from agg
    order by bag_type, capacity desc;
    
        BAG_ID BAG_TYPE   CAPACITY  ALLOCATED
       ------ -------- ---------- ----------
         1 A               500        500 
         2 A               300        300 
         3 A               100         50 
         4 B               200        200 
         5 B               100        100 
    

    Note that the order of the allocation is important if you want to minimize the waste capacity and finding an optimal allocation using different orders could be hard.

提交回复
热议问题