erp1022
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.Val ue/COUNT(F ields!Tran s.Value))* COUNT(Fields!Trans.Value)) )/COUNT(Fi elds!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?
Thanks.
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.Val
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?
Thanks.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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?
So if my weighted average is based on a count of transactions [COUNT(Trans)] * an amount, how would I write my code in SQL?
Perhaps it would be best if you could work up some sample source data, and then the output you would expect given that input.
ASKER
Please see attachment...
Weighted-Average.xls
Weighted-Average.xls
try this query
select transtype,
count(items),
sum(amount),
sum(amount * items) * 1.0 / sum(amount) as weight_avg
from yourtable
group by transtype
with rollup
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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)
select @weighted_average+=sum(wei
have not tried it such that not sure whether it is even valid.