计算单个查询中的加权平均值

时间:2014-10-07 10:50:44

标签: sql

示例数据:

table A
part    rating   numReviews
A308    100      7
A308    98       89

我正试图获得上述数据的平均评分。

需要的是每行rating * numReviews的总和除以总numReviews

这就是我正在尝试的但却给出了错误的结果(49.07,应该是98.15):

select part, 
cast((AVG(rating*numReviews)/sum(numReviews)) as decimal(8,2)) as rating_average
from A group by part order by part

这可以在一个查询中完成吗?我正在使用SQL Server

1 个答案:

答案 0 :(得分:15)

回到加权平均的定义,所以使用sum() s和除法:

select part, sum(rating * numreviews) / sum(numreviews) as rating_average
from a
group by part
order by part;

如果您愿意,可以将其转换为小数:

select part,
       cast(sum(rating * numreviews) / sum(numreviews) as decimal(8, 2)) as rating_average
from a
group by part
order by part;