SQL循环或替代

时间:2016-10-24 14:36:17

标签: sql-server tsql

我正在尝试按营业额的一天收集时间戳,它必须现场直播,因此我无法存储数据。

所以基本原则是我需要查看创建作业的时间,然后查看交付日期是否在某个时间段内。然后这给了我一个结果。然后,我需要循环显示该月的总天数。

下面的代码以一种方式工作,它收集数据,但它不会在1次提取中吐出来。

我需要一个程序来收集各种数据的时间戳功能

DECLARE @a int; 
Set @a = 1
While @a <=31
Begin

Select

'2016-10-' + convert(varchar(3),@a),
Sum(mjob.Value) as value

From jobdetails as mjob

Where mjob.createDate <= '2016-10-' + convert(varchar(3),@a)

 --this has to increment based on the @a
AND mjob.DeliveryTime between '2016-10-01' and '2016-11-01'--this stays the same throughout the given month

Set @a = @a +1

END

1 个答案:

答案 0 :(得分:0)

SUM()也可以用作窗口函数,使用<window frame preceding>来获取累积总和。

至少在MS Sql Server 2012及以后

select createDate, 
sum(Value) over (partition by year(createDate), month(createDate) order by createDate rows unbounded preceding) AS CumulativeValue
from JobDetails
where CreateDate between '2016-10-01' and '2016-10-31'
and DeliveryTime between '2016-10-01' and '2016-11-01';
相关问题