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
=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.
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.
To find the weighted mean: Multiply the numbers in your data set by the weights. Add the results up.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With