0

我试图在我的 sql 查询中使用这个数学公式来计算 EAM

EAM = 1/n * sum(abs(xi - avg(x)))

xi:是我在每个月的集合中的行的值。n:等于 1、2 或 3(取决于前 3 个月的存在情况)


DROP TABLE IF EXISTS Test;

CREATE TABLE Test (
[Product] varchar(10),
Year int NULL,
Quarter int NULL, 
Month int NULL,
Value float NULL,
)

INSERT INTO Test

Values ('P1', 2002, 1,  1,  99.54),
 ('P2', 2002,   1,  1,  69.02),
 ('P3', 2002,   1,  1,  94.96),
 ('P4', 2002,   2,  1,  49.54),
 ('P1', 2002,   2,  2,  64.98),
 ('P2', 2002,   2,  2,  10.00),
 ('P3', 2002,   3,  2,  74.81),
 ('P1', 2002,   3,  3,  55.12),
 ('P2', 2002,   3,  3,  95.66),
 ('P3', 2002    ,4  ,3, 43.69),
 ('P1', 2002    ,4  ,4, 83.33),
 ('P2', 2002    ,4  ,4, 33.16)

select [Product]
     , [Year]
     , [Month]
     , [Value]
     , n
     , avg_yi
     , EAM as 'EAM_CT'
from (
         select [Product]
              , [Year]
              , [Month]
              , [Value]
              , n                                                                                                             as 'n'
              , avg_yi                                                                                                        as 'avg_yi'
              , 1 / CONVERT(float, n) * sum(abs(Value - avg_yi))
                                            OVER (PARTITION BY [Product],[Year] ORDER BY Product,[Year] ASC ROWS 2 PRECEDING) as 'EAM'

         from (
                  select [Product]
                       , [Year]
                       , [Month]
                       , [Value]
                       , round(avg([Value])
                                   OVER (PARTITION BY [Product],[Year] ORDER BY [Product],[Year] ASC ROWS 2 PRECEDING),
                               2)                                                                                  as 'avg_yi'
                       , count([Month])
                               OVER (PARTITION BY [Product],[Year] ORDER BY [Product],[Year] ASC ROWS 2 PRECEDING) as 'n'

                  from [GlassFloor_Data].[dbo].[Test] as source_data ` enter code here `
              ) as volatilite
     ) as final_parameters

问题是过去 3 个月(如果存在)或过去 1 或 2 个月(如果前几个月的数量少于 3)的平均值需要相同。但实际上,使用的平均值是每行的平均值。 实际和预期结果

4

0 回答 0