简体   繁体   English

T-SQL-按顺序每4个月计算一次平均值

[英]T-SQL - Calculate Average for every 4 month sequentially

I have the following table: 我有下表:

Column1 Date         Data  Column2   Avg
Test1   01/01/2019     1     2
Test1   01/20/2019     2     3
Test1   01/23/2019     3     4
Test1   02/20/2019     4     3
Test1   03/20/2019     5     1
Test1   04/20/2019     6     2
Test1   05/20/2019     7     0
Test1   06/20/2019     8     1
Test1   07/20/2019     9     1
Test1   08/20/2019     10    2
Test1   09/20/2019     11    3
Test1   10/20/2019     12    4
Test1   01/01/2020     13    6
Test1   02/01/2020     14    8
Test1   03/01/2020     15    9
Test1   04/01/2020     16    1

I need a column in a select statement to Temp table that creates an additional column called Avg which would Take the values sequentially from Column2 and divide it by (Average of Data for every 4 month Divided by 30). 我需要在Temp表的select语句中的列中创建一个称为Avg的附加列,该列将按顺序从Column2中获取值并将其除以(每4个月的数据平均数除以30)。 So, for example, 因此,例如

  • the first Avg value would be 2 (from Column2)/ (Avg(1,2,3,4,5,6) (from Data column) /30) 第一个Avg值应为2(来自Column2)/(Avg(1,2,3,4,5,6)(来自Data列)/ 30)
  • the second Avg value would be 3 / (Avg(4,5,6,7) /30) 第二个Avg值为3 /(Avg(4,5,6,7)/ 30)
  • the Third Avg value would be 4 / (Avg(5,6,7,8) /30) 第三平均值将为4 /(Avg(5,6,7,8)/ 30)

And so on. 等等。

try this Fiddle : 试试这个小提琴

select f1.*, 
case when f3.Average30=0 then null else f1.Column2 / f3.Average30 end as Avg
from mytable f1
outer apply
(
  select avg(cast(f2.Data as decimal))/30.0 as Average30
  from mytable f2
  where f2.MyDate between f1.Mydate and EOMONTH(DATEADD(MONTH, 3, f1.MyDate))

) f3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM