如何将按分区表达式中的参数设置为行值,而不是设置为集合值?

时间:2019-08-27 12:37:35

标签: sql sql-server partition-by

我正在尝试在SQL查询中使用此数学公式来计算EAM

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

xi:是我每月每个集合中的行的值。         n:等于1、2或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,但是实际上,使用的平均值是每一行的平均值。  Actual and expected results

0 个答案:

没有答案