I need to calculate the average of Value_A
, Value_B
, and Value_C
in mssql.
My problem is that every information I need is in one row.
Every value has its own weight:
(sum of values * weight) / (sum weight):
Every column can be null. If there is a value but not a weight, weight is 100,
if there is a weight and no value then the specific value is not considered of course
e.g.
1st column:
(2*100+1*80)/(100+80)= 2.55 ≈ 2.6
2nd column:
(1*100+2*80)/(100+80)
+------+---------+---------+---------+----------+----------+----------+-----+
| ID | VALUE_A | VALUE_B | VALUE_C | Weight_A | Weight_B | Weight_C | AVG |
+------+---------+---------+---------+----------+----------+----------+-----+
| 1111 | 2 | 1 | null | 100 | 80 | 60 | 2.6 |
+------+---------+---------+---------+----------+----------+----------+-----+
| 2222 | 1 | 2 | null | 100 | 80 | 60 | |
+------+---------+---------+---------+----------+----------+----------+-----+
I got this far to get the AVG values without weights
select ID, VALUE_A, VALUE_B, VALUE_C, Weight_A, Weight_B, Weight_C,
(SELECT AVG(Cast(c as decimal(18,1)))
FROM (VALUES(VALUE_A),
(VALUE_B),
(VALUE_C)) T (c)) AS [Average]
FROM table
Second try was selecting sum of values multiply them by their weights and then divide them by sum of the weights. Sum of weights is missing. Can't figure out how to add it
select *,
(SELECT SUM(Cast(c as decimal(18,1)))
FROM (VALUES(VALUE_A* ISNULL(Weight_A,100)),
(VALUE_B* ISNULL(Weight_B,100)),
(VALUE_C* ISNULL(Weight_C,100))
) T (c)) AS [Average]
FROM table