【问题标题】:Map multiple rows based on cumulative value to another reference row in the same table根据累积值将多行映射到同一个表中的另一个引用行
【发布时间】:2022-01-18 00:20:33
【问题描述】:

我有如下 SQL 表:

PO Delivery_Type Scheduled_Line_Item Date Quantity
100 Scheduled Delivery 01 01/12/2021 100,000
100 Scheduled Delivery 02 07/12/2021 75,000
100 Actual Delivery NULL 03/12/2021 50,000
100 Actual Delivery NULL 12/12/2021 50,000
100 Actual Delivery NULL 15/12/2021 20,000
100 Actual Delivery NULL 31/12/2021 55,000

我正在尝试根据交货日期的顺序将实际交货项目映射到特定的 Scheduled_Line_Item,以产生如下结果:

PO Delivery_Type Scheduled_Line_Item Date Delivered_Qty Scheduled_Qty
100 Actual Delivery 01 03/12/2021 50,000 100,000
100 Actual Delivery 01 12/12/2021 50,000 100,000
100 Actual Delivery 02 15/12/2021 20,000 75,000
100 Actual Delivery 02 31/12/2021 55,000 75,000

从上面可以看出,前两行映射到“Scheduled_Line_Item”“01”,因为 Date 的序列已经完成了 Scheduled Delivery 中数量的前 100,000 个。一旦“实际交付”完成了第一个“计划交付”,那么只有我们移动到下一个“计划交付”,这就是为什么接下来的两行映射到“Scheduled_Line_Item”“02”。

我找到了此方法,但无法将其应用于我的要求https://sqlsunday.com/2019/09/16/calculating-invoice-settlements/

【问题讨论】:

  • 根据问题指南,请展示您的尝试并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。

标签: sql sql-server self-join


【解决方案1】:

假设 PO + Date 对于“实际交付”是唯一的,您可以匹配不包括重复行的运行总计

with sd as (
   select *, sum(Quantity) over(partition by PO order by date) s
   from tbl
   where Delivery_Type ='Scheduled Delivery'
),
ad  as (
  select *, sum(Quantity) over(partition by PO order by date) s
   from tbl
   where Delivery_Type ='Actual Delivery'
)
select top(1) with ties sd.*, ad.*
from sd
left join ad on ad.PO=sd.PO and sd.s>= ad.s 
order by row_number() over(partition by ad.PO, ad.Date order by sd.date)

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 2021-10-30
    • 2012-12-28
    • 2022-11-16
    • 2019-06-04
    • 2015-01-29
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多