简体   繁体   中英

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). So, for example,

  • the first Avg value would be 2 (from Column2)/ (Avg(1,2,3,4,5,6) (from Data column) /30)
  • the second Avg value would be 3 / (Avg(4,5,6,7) /30)
  • the Third Avg value would be 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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