在SQL中,您将如何根据每一行的容量将扣除额分配给每一行?

In SQL, how will you distribute the deduction to each row based on each row's capacity?

我在 sql 中有一个 table,其中包含以下列。第一个 table 显示收到的数量,第二个 table 显示发货的数量。第二个 table 为我们提供了 SKU 1 的总数量 70 和 SKU 2 的总数量 60。

Received Table
Id  Sku Quantity
1   1   30       
2   1   20
3   1   100
4   2   600

Shipped Table
Id  Sku  Quantity 
1   1    50
2   1    20
3   2    60 

我需要一个视图来显示相对于收到的发货数量 table。现在我想在这个 table 的每一行中分配每个 SKU 的总数,这应该给我以下结果:

ID   Sku   Quantity   Used    Remaining
1    1     30         30      0
2    1     20         20      0
3    1     100        20      80
4    2     600        60      540

您需要累加和聚合。以下是一行中总发货数量的累积总和:

select r.*, cume.cumequantity, coalesce(s.shipped ,0)
from received r cross apply
     (select sum(r2.quantity) as cumequantity
      from received r2
      where r2.sku  = r.sku and r2.id <= r.id
     ) cume left join
     (select s.sku, sum(quantity) as shipped
      from shipped s
      group by s.sku
     ) s
     on r.sku = s.sku

这提供了回答问题所需的基本信息。剩下的只是算术和逻辑:

with rs as (
      select r.*, cume.cumequantity, coalesce(s.shipped ,0)
      from received r cross apply
           (select sum(r2.quantity) as cumequantity
            from received r2
            where r2.sku  = r.sku and r2.id <= r.id
           ) cume left join
           (select s.sku, sum(quantity) as shipped
            from shipped s
            group by s.sku
           ) s
           on r.sku = s.sku
     )
select rs.ID, rs.Sku, rs.Quantity,
       (case when rs.cumequantity <= rs.shipped
             then rs.quantity
             when rs.cumquantity > rs.shipped and
                  rs.cumquantity - rs.quantity < rs.shipped
             then rs.shipped - rs.cumquantity - rs.quantity
             else 0
        end) as used,
       (case when rs.cumequantity <= rs.shipped
             then 0
             when rs.cumequantity > rs.shipped and
                  rs.cumequantity - rs.quantity < rs.shipped
             then rs.quantity - (rs.shipped - rs.cumequantity - rs.quantity)
             else rs.quantity
        end) as remaining
from rs