【问题标题】:Update order items with box quantity [closed]用盒子数量更新订单项目[关闭]
【发布时间】:2021-12-17 11:32:01
【问题描述】:

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

我需要的是例如下面的 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 Server 查询来处理这个问题?

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

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

【问题讨论】:

  • 你也需要解释一下逻辑。您如何确定 3 个数字 21 21 8 和任何其他组合,例如 48 1 1
  • @Squirrel - 逻辑是1 框中允许的最大值为 21,我们知道总共有 3 框。所以box 1 包含21box 2 包含21box 3 包含50-21-21 - 这有意义吗?一个框只能包含max
  • 所以需要的逻辑是按照 LineItem 的升序填充?
  • 在这种情况下,您将需要一个窗口函数或类似函数来计算金额,可能使用可更新的 CTE。
  • 我建议更新您的问题,澄清您在 cmets 中提供的信息。

标签: sql sql-server tsql sql-server-2016


【解决方案1】:

sum()与窗口函数一起使用来获取累计总数并将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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多