Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Weighted Average - Dropping Weights for NULL values

So there's the SQL Function AVG(), which takes the average of all values in a column, ignoring all NULL values. If one needs to make a weighted average, then they'd just use SUM(value * weight)/SUM(weight) with a Group By clause.

If I would want to do the latter, but some of my values are NULL, then how would I go about telling SQL to ignore weights with NULL value observations in the SUM(weight) function?

My other issue is that I'm taking an average of 90 different columns at once, so I'd like to avoid making 90 new weight variables for this calculation.

Let me know if I've made this clear or not.

I'm using SQL Server 2005

like image 409
Jared Avatar asked Mar 01 '13 18:03

Jared


People also ask

How do you find the Non Zero weighted average in Excel?

=AVERAGEIF(A1:A11,"<>0") This formula eliminates zero values as a result of the criteria expression and Blank cells as default functionality of AVERAGEIF function, so it only counts cells in Excel average without zeros and average if not blank.

How do I do a weighted average in Excel?

To calculate the weighted average in Excel, you must use the SUMPRODUCT and SUM functions using the following formula: =SUMPRODUCT(X:X,X:X)/SUM(X:X) This formula works by multiplying each value by its weight and combining the values. Then, you divide the SUMPRODUCT but the sum of the weights for your weighted average.

How do you find the weighted mean of ungrouped data?

To find the weighted mean: Multiply the numbers in your data set by the weights. Add the results up.


1 Answers

You would use conditional summing as the denominator:

select sum(value*weight) / sum(case when value is not null then weight else 0 end)

If the weights are always bigger than 0, then you don't have to worry about divide by 0. That would only occur when all the values are NULL. And, in that case the numerator would be NULL.

You could also phrase it as:

select sum(value*weight) / sum(case when value is not null then weight end)

or as:

select sum(case when value is not null then value*weight end) / sum(case when value is not null then weight end)

This is more verbose, but makes it very clear that you are ignoring NULL values in both the numerator and denominator.

like image 114
Gordon Linoff Avatar answered Sep 19 '22 08:09

Gordon Linoff