Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate weighted average in single query

Tags:

sql

Example data:

table A
part    rating   numReviews
A308    100      7
A308    98       89

I'm trying to get the average rating for the above data.

What it needs to be is the sum of rating*numReviews for each line divided by the total numReviews

This is what I'm trying but it's giving incorrect result (49.07, should be 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

Can this be done in a single query? I'm using SQL Server

like image 884
StudioTime Avatar asked Oct 07 '14 10:10

StudioTime


1 Answers

Just go back to the definition of weighted average, so use sum()s and division:

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

You can convert this to a decimal if you like:

select part,
       cast(sum(rating * numreviews) / sum(numreviews) as decimal(8, 2)) as rating_average
from a
group by part
order by part;
like image 105
Gordon Linoff Avatar answered Sep 26 '22 00:09

Gordon Linoff