如何根据特定列拆分行值?

How to split row value according to specific column?

我有 Table A 和 Table B,我无法在 Table B 中获取已完成的数量,其中已完成数量的总和等于 [中的可用字段=26=] A.

对于商品 ID 1,可用数量在 Table A 和 Table B 中为 99 此商品 ID 1 有不同的货架,数量为 99,只能满足 60 数量机架 A 和机架 B 的剩余 39 数量。

Table一个

ID   Available
1    99
2    5

Table B

ID  Rack  Required 
1    A    60    
1    B    102    
1    C    8    
2    A    10

期望的结果

ID   Rack Required    Fulfilled 
1    A    60          60    
1    B    102         39    
1    C    8           0    
2    A    4           4
2    B    2           1

我试过使用下面的查询,但似乎无法获得预期的结果

SELECT ID,
       RACK,
       REQUIREDQTY,
       SUM(FULFILLEDQTY) OVER (ORDER BY ID,
                                        RACK,
                                        rows between unbounded preceding and 1 preceding) AS FULFILLEDQTY
FROM TABLEB
     LEFT JOIN TABLEA ON TABLEB.ID = TABLEA.ID;

使用 sum(Required) over (...) 并检查 Available

select A.ID, B.Rack, B.Required,
       Fulfilled = case when sum(B.Required) over (partition by A.ID order by B.Rack) 
                        <=   A.Available
                        then B.Required
                        when sum(B.Required) over (partition by A.ID order by B.Rack) 
                        -    B.Required <= A.Available
                        then A.Available 
                        -    sum(B.Required) over (partition by A.ID order by B.Rack) 
                        +    B.Required
                        else 0
                        end
from   A
       inner join B on A.ID = B.ID
order by A.ID, B.Rack       

db<>fiddle demo


编辑:由于结构变化(附加列rack

select A.ID, A.rack, B.bin, B.Required,
       Fulfilled = case when sum(B.Required) over (partition by A.ID, A.rack 
                                                       order by B.bin) 
                        <=   A.Available
                        then B.Required
                        when sum(B.Required) over (partition by A.ID, A.rack 
                                                       order by B.bin) 
                        -    B.Required 
                        <=   A.Available
                        then A.Available 
                        -    sum(B.Required) over (partition by A.ID, A.rack
                                                       order by B.bin) 
                        +    B.Required
                        else 0
                        end
from   A
       inner join B on A.ID = B.ID and A.rack = B.rack
order by A.ID, A.rack,  B.bin