SQL 中的计算加权平均值
Calculated Weighted Average in SQL
我正在尝试计算每个月的 YTD 值。我怎样才能在 SQL 服务器中实现这一点?
绿色是我的数据在 table.I 中的样子,我想计算黄色的数据。非常感谢您的帮助。
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)
如果您的 SQL 服务器版本支持,您可以使用 window 函数 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
请注意,该值每年都会重置。
编辑:对于 SQL 支持 outer apply
.
的低于 2012 的服务器版本
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
您可以使用 sum
的 window 变体求和以计算 运行 总数:
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
我正在尝试计算每个月的 YTD 值。我怎样才能在 SQL 服务器中实现这一点?
绿色是我的数据在 table.I 中的样子,我想计算黄色的数据。非常感谢您的帮助。
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)
如果您的 SQL 服务器版本支持,您可以使用 window 函数 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
请注意,该值每年都会重置。
编辑:对于 SQL 支持 outer apply
.
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
您可以使用 sum
的 window 变体求和以计算 运行 总数:
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