使用列sql的累积总和更新库存

时间:2017-08-04 04:46:15

标签: sql sql-server sql-server-2008

我有一个包含列ID,日期和股票的数据库表。我想添加一个名为Order的列,在开始时显示为1,为零,直到下一个累积和达到1。

以下是我的示例数据 - 所需结果位于示例订单列中:

stdp

2 个答案:

答案 0 :(得分:0)

只需将@t替换为您的表名:

select id, date, stock, cumu_val, case when cumu_val = 0 then 1 when intval <> lastintval then 1 else 0 end as [order]
from
(
    SELECT id, date, stock, (SELECT ISNULL(SUM(stock), 0) FROM @t WHERE date < t.date) as cumu_val, 
        FLOOR((SELECT ISNULL(SUM(stock), 0) FROM @t WHERE date < t.date)) intval, 
        FLOOR((SELECT ISNULL(SUM(stock), 0) FROM @t WHERE date < (select top 1 date from @t where date < t.date order by date desc))) lastintval
    FROM @t t
)sq

这里有一些示例输出

id   date          stock    cumu_val    order
1    2017-01-01    0.17     0.00        1
1    2017-02-01    0.37     0.17        0
1    2017-03-01    0.57     0.54        0
1    2017-04-01    0.67     1.11        1
1    2017-05-01    0.37     1.78        0
1    2017-06-01    0.27     2.15        1
1    2017-07-01    0.17     2.42        0
1    2017-08-01    0.70     2.59        0
1    2017-09-01    0.17     3.29        1
1    2017-10-01    0.07     3.46        0
1    2017-11-01    0.07     3.53        0
1    2017-12-01    0.17     3.60        0
1    2018-01-01    0.27     3.77        0
1    2018-02-01    0.37     4.04        1

答案 1 :(得分:0)

select [id],[date],[stock],IIF([cumstock] is null , 0 , [cumstock]) [cumstock] ,
IIF(cumstock_lag is null and cumstock is null,1,IIF(cumstock_lag is null, 0 , IIF(floor(cumstock_lag)<>floor(cumstock) , 1 , 0 ) ) ) [reorder]  
from (
   select [id],[date],[stock],lag_date,
        (select sum(t4.[stock]) from dbo.teststock t4 where t4.[date] < t3.[lag_date]) as [cumstock_lag],
        (select sum(t5.[stock]) from dbo.teststock t5 where t5.[date] <= t3.[lag_date]) as [cumstock] 
        from (
            select [id],[date],[stock],(select max(t2.[date]) from dbo.teststock t2 where t2.[date] < t.[date]) as [lag_date]  from dbo.teststock t 
    ) t3
) t6

假设日期是唯一的, 使用两个嵌套的比较比较来生成以下内容,以构建可以使用2012+的窗口函数完成的滞后结构。累积和是使用select子句中的子查询构建的。

1   2017-01-01  0.17    0   1
1   2017-02-01  0.17    0.17    0
1   2017-03-01  0.17    0.34    0
1   2017-04-01  0.17    0.51    0
1   2017-05-01  0.17    0.68    0
1   2017-06-01  0.17    0.85    0
1   2017-07-01  0.17    1.02    1
1   2017-08-01  0.17    1.19    0
1   2017-09-01  0.17    1.36    0
1   2017-10-01  0.17    1.53    0
1   2017-11-01  0.17    1.7 0
1   2017-12-01  0.17    1.87    0
1   2018-01-01  0.17    2.04    1
1   2018-02-01  0.17    2.21    0
1   2018-03-01  0.17    2.38    0
1   2018-04-01  0.17    2.55    0
1   2018-05-01  0.17    2.72    0
1   2018-06-01  0.17    2.89    0
1   2018-07-01  0.17    3.06    1
1   2018-08-01  0.17    3.23    0
1   2018-09-01  0.17    3.4 0
1   2018-10-01  0.17    3.57    0
1   2018-11-01  0.17    3.74    0