我正在使用sql Server 2012来构建库存计划/重新订购引擎.
我有一堆过时的交易,称之为信用和借记.我想一次做两件事:
>生成运行总计(每日净余额)
>生成补充建议.补充将重置运行
总计(#1)回零.
该表如下所示:
CREATE TABLE TX (TDate DATETIME,Qty INT); INSERT INTO TX VALUES ('2014-03-01',20); INSERT INTO TX VALUES ('2014-03-02',-10); INSERT INTO TX VALUES ('2014-03-03',-20); INSERT INTO TX VALUES ('2014-03-04',-10); INSERT INTO TX VALUES ('2014-03-05',30); INSERT INTO TX VALUES ('2014-03-06',-20); INSERT INTO TX VALUES ('2014-03-07',10); INSERT INTO TX VALUES ('2014-03-08',-20); INSERT INTO TX VALUES ('2014-03-09',-5);
我正在使用sql 2012 SUM OVER()窗口函数来显示这些的运行总计.
select TDate,Qty,RunningTotal,RecommendedReplenish from ( select TDate,SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED PRECEDING) as RunningTotal,-1 * (CASE WHEN Qty < 0 AND SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED PRECEDING) < 0 THEN CASE WHEN Qty > SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED PRECEDING) THEN Qty ELSE SUM(Qty) OVER (ORDER BY TDate ROWS UNBOUNDED PRECEDING) END ELSE 0 END) as RecommendedReplenish /* Wrong,does not account for balance resetting to zero */ from TX ) T order by TDate
如果它低于零,我需要找到一种方法将运行总计(也就是RT)重置为零.
我的查询,其中Qty和RT均为负数,并将这些数据作为第一次推荐补充的更大(更少负面).这是第一次正常工作.
我不知道如何从窗口运行总计中扣除这个…如果可能的话,我想在单个语句中执行此操作.
TDate Qty R.Tot Replenish New RT ----------- ---- ----- ----------- --------- 3/1/2014 20 20 20 3/2/2014 -10 10 10 3/3/2014 -20 -10 10 0 3/4/2014 -10 -20 10 0 3/5/2014 30 10 30 3/6/2014 -20 -10 10 3/7/2014 10 0 20 3/8/2014 -20 -20 0 3/9/2014 - 5 -25 5 0
Itzik Ben-Gan,Joe Celko或其他sql英雄,你在外面吗?