【问题标题】:Cumulative table in SQL ServerSQL Server 中的累积表
【发布时间】:2021-09-30 20:24:11
【问题描述】:

我有两张表:一张是按月预测的 SKU,另一张是收到的订单。

预测

Year Month SKU QTY
2021 1 A01 100
2021 2 A01 300
2021 3 A01 500

订单

Date SKU QTY
2021-01-01 A01 40
2021-01-03 A01 200
2021-01-28 A01 325

我想要做的是一个表格,用于确定每次新订单到来时您使用的 Forecast 来自哪个预测。我想用 SQL 构建的表应该是这样的:

Date SKU Total Order Fraction Order Total Forecast Initial Remaining Fcast_Month
2021-01-01 A01 40 40 100 100 60 1
2021-01-03 A01 200 60 100 60 0 1
2021-01-03 A01 200 140 300 300 160 2
2021-01-28 A01 325 160 300 160 0 2
2021-01-28 A01 325 165 500 500 335 3

当剩余预测小于订单时,列分数订单是订单的拆分。订单可以在预测年份和月份之前或之后到达,因此无法合并日期,但必须按逻辑顺序消费预测(1 月应该先到,然后是 2 月,依此类推)。

我认为这可以通过在 SQL 中执行 while 循环来解决,但我还没有弄清楚。请帮忙:)

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    我冒昧地将forecastorders 表剥离到了解问题要点所需的最低限度:

    据我所知,这是一个解决问题的 while 循环:

    DECLARE @xactions TABLE (
        XactNum int IDENTITY(1,1),
        TakeAmount int,
        ForecastRemaining int,
        OrderRemaining int,
        ForecastMonth int, OrderNum int
    );
    
    DECLARE @forecastMonth int;
    DECLARE @forecastRemaining int;
    DECLARE @orderNum int;
    DECLARE @orderRemaining int;
    DECLARE @takeAmount int;
    
    SELECT @forecastMonth = 1, @forecastRemaining = Qty FROM forecast WHERE [Month] = 1;
    
    SELECT @orderNum = 1, @orderRemaining = Qty FROM orders WHERE OrderNum = 1;
    
    WHILE @orderRemaining > 0
    BEGIN
        SET @takeAmount = iif(@forecastRemaining > @orderRemaining, @orderRemaining, @forecastRemaining);
    
        SET @forecastRemaining -= @takeAmount;
        SET @orderRemaining -= @takeAmount;
    
        INSERT @xactions ( TakeAmount, ForecastMonth, OrderNum, ForecastRemaining, OrderRemaining )
        VALUES ( @takeAmount, @forecastMonth, @orderNum, @forecastRemaining, @orderRemaining );
    
        IF @forecastRemaining = 0
        BEGIN
            SET @forecastMonth += 1;
            SET @forecastRemaining = ISNULL((SELECT Qty FROM forecast WHERE [Month] = @forecastMonth), 0);
        END
    
        IF @orderRemaining = 0
        BEGIN
            SET @orderNum += 1;
            SET @orderRemaining = ISNULL((SELECT Qty FROM orders WHERE OrderNum = @orderNum), 0);
        END
    END
    
    SELECT * FROM @xactions ORDER BY XactNum;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多