[英]Calculated Weighted Average in SQL
I am trying to calculate the YTD value for every month. 我正在尝试计算每个月的YTD值。 How could I achieve this in SQL Server? 如何在SQL Server中实现呢?
Green is how my data looks in the table.I am suppose to calculate the one in Yellow. 表格中的数据是绿色,我想以黄色计算。 Your help will be much appreciated. 您的帮助将不胜感激。
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)
You can use the window function SUM
if your version of SQL Server supports it. 如果您的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
Note that the value resets every year. 请注意,该值每年重置一次。
Edit: For SQL Server versions below 2012 that support outer apply
. 编辑:对于支持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
You can use the window variant of sum
to sum to calculate running totals: 您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.