如果我在SQL SERVER中有一个表:
DATE ITEM Quantity_Received
1/1/2016 Hammer 20
1/3/2016 Hammer 50
1/5/2016 Hammer 100
...
我想输出:
DATE ITEM Quantity_Running
1/1/2016 Hammer 20
1/2/2016 Hammer 20
1/3/2016 Hammer 70
1/4/2016 Hammer 70
1/5/2016 Hammer 120
其中Quantity_Running只是累积总和。我对如何将丢失的日期添加到初始表中不存在的输出表感到困惑。注意,我需要为许多项目执行此操作,并且可能有一个包含我想要的日期的临时表。
谢谢!
修改
有没有办法让你使用内连接?
SELECT TD.Date,
FT1.Item,
SUM(FT2.QTY) AS Cumulative
FROM tempDates TD
LEFT JOIN FutureOrders FT1
ON TD.SETTLE_DATE = FT1.SETTLE_DATE
INNER JOIN FutureOrders FT2
ON FT1.Settle_Date < ft2.Settle_Date AND ft1.ITEM= ft2.ITEM
GROUP BY ft1.ITEM, ft1.Settle_Date
tempDates是一个具有我想要的日期的CTE。因为我然后返回NULL值。对不起,但是为了让它变得更复杂我真的想要:
DATE ITEM Quantity_Running
1/1/2016 Hammer 150
1/2/2016 Hammer 100
1/3/2016 Hammer 100
1/4/2016 Hammer 0
1/5/2016 Hammer 0
以为我能够根据我更简单的问题自己得到答案。
答案 0 :(得分:3)
使用递归cte生成所有日期(对于指定的日期范围)。此后,在生成的日期cte上保持联接,并获取缺失日期的运行总和。
with dates_cte as
(select cast('2016-01-01' as date) dt
union all
select dateadd(dd,1,dt) from dates_cte where dt < '2016-01-31' --change this date to the maximum date needed
)
select dt,item,sum(quantity) over(partition by item order by dt) quantity_running
from (select d.dt,i.item,
coalesce(t.quantity_received,0) quantity
from dates_cte d
cross join (select distinct item from t) i
left join t on t.dt=d.dt and i.item=t.item) x
order by 2,1
编辑:要获取不包括当前行的反向累计和,请使用
with dates_cte as
(select cast('2016-01-01' as date) dt
union all
select dateadd(dd,1,dt) from dates_cte where dt < '2016-01-31' --change this date to the maximum date needed
)
select dt,item,
sum(quantity) over(partition by item order by dt desc rows between unbounded preceding and 1 preceding) quantity_running
from (select d.dt,i.item,
coalesce(t.quantity_received,0) quantity
from dates_cte d
cross join (select distinct item from t) i
left join t on t.dt=d.dt and i.item=t.item) x
order by 2,1