Avatar of erp1022
erp1022Flag for United States of America asked on

calculating a weighted average in SQL, SSRS

Hello Experts,

Does anyone know how to calculate a weighted average in SQL?

First I get the average of something: COUNT(transactions)/Fee = Average
Then to get the weighted average I would have to total the above values of 'Average' for the three different transactions types we use, and then divide that by the total count.

I cannot create a calculated field because in SSRS you can't use aggregate functions in a calc field. Also, in SSRS, I have tried creating an expression:

=(SUM((Fields!CRDTAMNT.Value/COUNT(Fields!Trans.Value))* COUNT(Fields!Trans.Value)))/COUNT(Fields!Trans.Value)

and I keep getting errors about nested aggregate functions.

So first of all, should I do this in my query or somewhere in SSRS?
Second of all, what is the code/syntax to achieve this?


SSRSMicrosoft SQL Server 2008Microsoft SQL Server

Avatar of undefined
Last Comment

8/22/2022 - Mon

You have the value and the weight in each row or you know the weights.
in either case you would first sum the weights into a variable and then use the formula of wight*value/sum(weights)

select @total_weight=sum(weights) from table;
select @weighted_average+=sum(weights*values/@total_weight) from table;

have not tried it such that not sure whether it is even valid.
Patrick Matthews

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

Okay now I'm really confused.

So if my weighted average is based on a count of transactions [COUNT(Trans)] * an amount, how would I write my code in SQL?
Patrick Matthews

Perhaps it would be best if you could work up some sample source data, and then the output you would expect given that input.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.

Please see attachment...

try this query
select 	transtype,
	sum(amount * items) * 1.0 / sum(amount) as weight_avg
from yourtable
group by transtype
with rollup

Open in new window

Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.