SQL-库存持久算法

时间:2019-01-25 11:25:47

标签: sql algorithm tsql forecasting

要求是这样的。我们想知道在给定的第+1个月至第+ x个月的预测下,存货数量将持续多长时间

逻辑是:

quantity / forecastNextMonth

但是

if quantity > forecastNextMonth then
(1 + (quantity - forecastNextMonth)) / forecastNextMonth+2

这也应该适用于month + 3,因此处理案件的东西会很快变得混乱。

if quantity > forecastNextMonth+2 then
(1 + (quantity - (forecastNextMonth + forecastNextMonth+2))) / forecastNextMonth+3

最后的解决方案还必须检查0的bc值除以零误差。

这是一个用于摆弄的sql示例。 我不敢在数学上更好地说明这一点。

create table #Temp
(
    Id int,
    Quantity decimal(10,2),
    Forecast decimal(10,2),
    WhatEverTimeStamp datetime,
    InventoryLasting decimal(4,2)
)

insert into #Temp
(Id, Quantity, Forecast, WhatEverTimeStamp)
VALUES
(1, 10, 0, '2019-01-01'),
(2, 20, 10, '2019-01-01'),
(3, 30, 30, '2019-01-01'),
(4, 100, 20, '2019-01-01'),
(5, 0, 10, '2019-01-01'),
(6, 0, 0, '2019-01-01')
;

SELECT
Id, Quantity, Forecast, WhatEverTimeStamp
, convert(decimal(4,2),
CASE WHEN Quantity > 0  
THEN
    CASE WHEN Quantity >= LEAD(Forecast, 1) OVER (PARTITION BY WhatEverTimeStamp ORDER BY WhatEverTimeStamp) 
    THEN
        CASE WHEN LEAD(Forecast, 2) OVER (PARTITION BY WhatEverTimeStamp ORDER BY WhatEverTimeStamp) > 0
        THEN
            1 + ((Quantity - LEAD(Forecast, 1) OVER (PARTITION BY WhatEverTimeStamp ORDER BY WhatEverTimeStamp))
            /
            LEAD(Forecast, 2) OVER (PARTITION BY WhatEverTimeStamp ORDER BY WhatEverTimeStamp))
        ELSE
            CASE WHEN Forecast > 0 THEN Quantity / Forecast ELSE 0 END
        END
    ELSE
        CASE WHEN Forecast > 0 THEN Quantity / LEAD(Forecast, 1) OVER (PARTITION BY WhatEverTimeStamp ORDER BY WhatEverTimeStamp)  ELSE 99 END
        --11
    END
ELSE
    0
END) AS InventoryLasting

FROM
#Temp


If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

对于ID 4案例,此案例声明不完整,因为它太长了,我试图在小提琴上方描述它。 需求排除了使用平均预测的解决方案。

0 个答案:

没有答案