给出最终值的库存重新计算

时间:2018-05-22 04:00:33

标签: sql sql-server tsql sql-server-2014

我正在编写一个SQL Server脚本,根据实际库存,在过去365天内从今天开始重新计算特定SKU。在脚本中我做了很多数据清理操作。最后,输出是从临时表生成的,如下所示:

SELECT
    DATE,
    SUM(CASE WHEN MOV='IN' THEN 1 ELSE 0 END) AS TRANSACTION_IN, --COUNT TRANSACTIONS IN
    SUM(CASE WHEN MOV='OUT' THEN 1 ELSE 0 END) AS TRANSACTION_OUT, --COUNT TRANSACTIONS OUT
    SUM(CASE WHEN MOV ='IN' THEN QTD ELSE 0 END) AS SUM_IN, --SUM QUANTITY IN
    SUM(CASE WHEN MOV ='OUT' THEN QTD ELSE 0 END) AS SUM_OUT --SUM QUANTITY IN
FROM #MOVIMENTS
GROUP BY DT
ORDER BY DT

Bellow可以看到显示的SQL的输出示例:

Table example

该表显示了按日期分组的交易总额以及仓库的数量IN和OUT。我的目的是添加一个名为“STOCK”的列,该列显示所代表日期的SKU的库存水平。为此,我所拥有的是实际库存水平。所以我需要的是在所有日期系列中逐日重新计算所有库存水平。

在Excel中很容易。我可以将实际级别放在最后一行(例如:10)并只是扩展计算(图像中显示的公式),直到我到达顶部。如图所示(列E是公式,列G是输出):

Inventory Recalculation on Excel

有人可以帮我在SQL Server中实现这个结果吗?

在Python中我使用Pandas找到了solution,但我更愿意在SQL Script中实现这个计算。

3 个答案:

答案 0 :(得分:1)

您需要一个运行(或窗口)总和。

;WITH PartialResults AS
(
    SELECT
        DATE,
        SUM(CASE WHEN MOV='IN' THEN 1 ELSE 0 END) AS TRANSACTION_IN, --COUNT TRANSACTIONS IN
        SUM(CASE WHEN MOV='OUT' THEN 1 ELSE 0 END) AS TRANSACTION_OUT, --COUNT TRANSACTIONS OUT
        SUM(CASE WHEN MOV ='IN' THEN QTD ELSE 0 END) AS SUM_IN, --SUM QUANTITY IN
        SUM(CASE WHEN MOV ='OUT' THEN QTD ELSE 0 END) AS SUM_OUT --SUM QUANTITY IN
    FROM #MOVIMENTS
    GROUP BY DT
)
SELECT
    P.*,
    RunningSum = SUM(P.SUM_IN + P.SUM_OUT) OVER (ORDER BY P.Date ASC)
FROM
    PartialResults AS P

答案 1 :(得分:0)

SQL FIDDLE Example

SELECT
    DATE,
    SUM(CASE WHEN MOV='IN' THEN 1 ELSE 0 END) AS TRANSACTION_IN, --COUNT TRANSACTIONS IN
    SUM(CASE WHEN MOV='OUT' THEN 1 ELSE 0 END) AS TRANSACTION_OUT, --COUNT TRANSACTIONS OUT
    SUM(CASE WHEN MOV ='IN' THEN QTD ELSE 0 END) AS SUM_IN, --SUM QUANTITY IN
    SUM(CASE WHEN MOV ='OUT' THEN QTD ELSE 0 END) AS SUM_OUT --SUM QUANTITY IN
INTO #newtable
FROM #MOVIMENTS t1
GROUP BY DT
ORDER BY DT

select t1.DATE, t1.TRANSACTION_IN, t1.TRANSACTION_OUT, t1.SUM_IN, t1.SUM_OUT, SUM(t2.SUM_IN + t2.SUM_OUT) as STOCK
from #newtable t1
inner join #newtable t2 on t1.DATE >= t2.DATE
group by t1.DATE, t1.TRANSACTION_IN, t1.TRANSACTION_OUT, t1.SUM_IN, t1.SUM_OUT
order by t1.DATE

答案 2 :(得分:0)

SQL Fiddle Example

根据@EzLo的想法,我找到了解决这个问题的方法。

DECLARE @cum_sum float -- scalar cumulated sum
DECLARE @last_stock float = 10 -- current stock level

-- get the last value of the cumulated sum 
SELECT TOP 1 @cum_sum = SUM(SUM_IN + SUM_OUT) OVER (ORDER BY Date ASC) FROM t ORDER BY DATE DESC

-- final select
SELECT 
  *,
  RunningSum = SUM(SUM_IN + SUM_OUT) OVER (ORDER BY Date ASC) - (@cum_sum - @last_stock)
FROM t

有更简单的方法吗?