Oracle aggregation function to allocate amount

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

    This should do the trick:

    select t1.bag_id
         , t1.bag_type
         , t1.capacity
         , least( t1.capacity -- don't over fill the bag
                , greatest( 0 -- don't under fill the bag
                          , t2.item_amount  -- to be allocated
                          - nvl(sum(t1.capacity) -- less previous allocations
                              over (partition by t1.bag_type
                                        order by t1.capacity desc
                                 rows between unbounded preceding and 1 preceding)
                               , 0))) Allocated
      from t1
      join t2
        on t2.item_type = t1.bag_type;
    
        BAG_ID B   CAPACITY  ALLOCATED
    ---------- - ---------- ----------
             1 A        500        500
             2 A        300        300
             3 A        100         50
             4 B        200        200
             5 B        100        100
    

提交回复
热议问题