SQL中计算的加权平均值

时间:2017-05-22 21:33:06

标签: sql sql-server weighted-average

我正在尝试计算每月的YTD值。我怎样才能在SQL Server中实现这一点?

enter image description here

绿色是我的数据在表格中的样子。我想以黄色计算。非常感谢您的帮助。

Year    Month   Monthly_Score   N_size  YTD_Score
2017    1        70             10       70*10/10
2017    2        80             20       70*10/(10+20) + 80 *20 /(10+20)
2017    3        90             30       70*10/(10+20+30) + 80 * 20 /(10+20+30) 
                                         +90*30/(10+20+30)

2 个答案:

答案 0 :(得分:2)

如果您的SQL Server版本支持,可以使用窗口函数SUM

select year,month,monthly_score,n_size,
1.0*sum(monthly_score*n_size) over(partition by year order by month)/
sum(n_size) over(partition by year order by month)
from yourtable

请注意,该值每年都会重置。

编辑:对于支持outer apply的2012年以下的SQL Server版本。

select y.year,y.month,y.monthly_score,y.n_size,t.ytd_score
from yourtable y
outer apply (select 1.0*sum(monthly_score*n_size)/sum(n_size) as ytd_score 
             from yourtable y1 
             where y.year=y1.year and y1.month<=y.month
            ) t

答案 1 :(得分:1)

您可以使用sum的窗口变量求和来计算运行总计:

SELECT [Year], [Month], [Monthly_Score], [N_Size],
       SUM([Monthly_Score] * [N_Size]) 
          OVER (ORDER BY [Year], [Month]
          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / 
      SUM([N_Size]) 
          OVER (ORDER BY [Year], [Month]
          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS YTD_Score
FROM  my_table