使用箱子数量更新订单项目

Update order items with box quantity

我正在尝试更新一个运输数据库,该数据库从一开始就使用 table 结构设置不正确,但我不得不使用它(现在)。

例如,我需要的是下面的 DDL 3 saleId 的总出货量 - 我需要让查询执行的是:

Create Table Testing
(
  saleId int
  ,totalQty int
  ,itemDescription varchar(250)
  ,lineItem int
  ,maxAllowedInBox int
  ,itemsInBox int
  ,totalBoxesShipped int
)

Insert Into Testing Values
('123', 50, 'shirt', 1, 21, 0, 3)
,('123', 50, 'socks', 2, 21, 0, 3)
,('123', 50, 'hat', 3, 21, 0, 3)

itemsInBox 的值更新为 21, 21, 8 因为 21+21+8 = 50(允许的最大值) 这只是数据的一个子集,但它说明了我需要做什么。我如何编写 SQL 服务器查询来处理这个问题?

我尝试了这个 update 查询,但它更新不准确,因为它没有考虑到我需要的所有内容。 :(

Update Testing
Set itemsInBox = 
case
      when [maxAllowedInBox] < totalQty then [maxAllowedInBox] 
      else [totalQty]-[maxAllowedInBox] 
end

使用sum()和window函数来获取累计总数并将maxAllowedInBox分配给除最后一行之外的所有行

update t
set    itemsInBox = case when cumTotal <= totalQty 
                         then maxAllowedInBox
                         else totalQty - cumTotal + maxAllowedInBox
                         end
from
(
    select *, 
           cumTotal = sum(maxAllowedInBox) over (partition by saleId 
                                                     order by lineItem)
    from   Testing
) t

db<>fiddle demo