2017-02-22 111 views
1

我想返回在結果數據集中每個月滾動12個月的平均值,但我不確定該如何執行此操作。T-SQL - 滾動12個月的平均值

我想下面的腳本將工作:

DECLARE @StartDate as datetime 
DECLARE @EndDate as datetime 
SET @StartDate = '01/04/2011' 
SET @EndDate = getdate() 

select x.FinYear, x.FinMonth, x.MonthText, avg(TimeSeconds) [AverageTimeSeconds] 
from times x 
where (x.TimeOfCall >= @StartDate and x.TimeOfCall < @EndDate) 
group by x.FinYear, x.FinMonth, x.MonthText 
order by x.FinYear, x.FinMonth 

但它只返回的月平均值,我如何獲得12個月的平均領導到每一個開始和結束日期之間的月份。

得到的數據集,我找的是如下:

Fin Year Fin Month Month Text Avg Time Seconds R12M Avg Seconds 
2015/16 01 Apr 100 101 
2015/16 02 May 95 98 
2015/16 03 Jun 103 100 
2015/16 04 Jul 110 100 
2015/16 05 Aug 100 100 
2015/16 06 Sep 90 97 
2015/16 07 Oct 93 97 
2015/16 08 Nov 98 100 
2015/16 09 Dec 80 98 
2015/16 10 Jan 88 98 
2015/16 11 Feb 100 98 
2016/17 12 Mar 115 100 
2016/17 01 Apr 105 100 
2016/17 02 May 98 100 
2016/17 03 Jun 95 98 
2016/17 04 Jul 102 98 
2016/17 05 Aug 109 99 
2016/17 06 Sep 104 100 
2016/17 07 Oct 98 98 
2016/17 08 Nov 99 97 
2016/17 09 Dec 90 97 

的連續12個月的平均不平均的月平均值,但平均12個月的有關領導到一個月。因此2017年1月將是​​2016年2月1日至2017年1月31日的平均值,2016年10月的平均值將爲2015年11月1日至2016年10月31日。

我希望你能幫忙:-)。

+1

請顯示您的預期結果,實際結果集和DDL以重新編制問題 – TheGameiswar

+0

也標記您正在使用的SQLServer版本。請查看此處的示例:https://spaghettidba.com/2015/04/24/how如果你在SQL 2012+上,這是你所需要的:https://www.simple-talk.com/sql/t-sql-sql-property-to-public-forum/ – TheGameiswar

+0

sql-programming/calculation-values-rolling-window-in-transact-sql/ – RoundFour

回答

1

如果你每個月的數據,那麼下面計算平均較前12個月(注意,這是整體平均,而不是平均的月平均值):

select x.FinYear, x.FinMonth, x.MonthText, avg(TimeSeconds)as [AverageTimeSeconds], 
     (sum(sum(TimeSeconds)) over (order by x.FinYear, x.FinMonth rows between 11 preceding and current row)/
     sum(count(*)) over (order by x.FinYear, x.FinMonth rows between 11 preceding and current row) 
     ) as avg_12month 
from times x 
where x.TimeOfCall >= @StartDate and x.TimeOfCall < @EndDate 
group by x.FinYear, x.FinMonth, x.MonthText 
order by x.FinYear, x.FinMonth; 

注意: where子句會影響12個月的回顧期。在其他情況下,回顧將不包括這個時期的前幾個月。

+0

謝謝,在這種情況下,第一次滾動的12個月的平均值將成爲數據集中的第12行,因爲第11次將是前11行的平均值,第5次將是前5行的平均值。 – msinghm

+0

@msinghm。 。 。是。這是如何工作的。 –

+0

非常感謝你,這完美的作品。我剛剛添加了OFFSET 12 ROWS;條款,並比預期的日期提前12個月運行,這對我有用。非常感謝你。 – msinghm