我需要在 mssql中计算Value_A
、Value_B
和的平均值。
我的问题是我需要的每一个信息都在一行中。Value_C
每个值都有自己的权重:
(sum of values * weight) / (sum weight):
每列都可以为空。如果有值但没有权重,则权重为100,
如果有权重而没有值,则当然不考虑具体值
例如
第一栏:
(2*100+1*80)/(100+80)= 2.55 ≈ 2.6
第二栏:
(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 | |
+------+---------+---------+---------+----------+----------+----------+-----+
我走了这么远来获得没有权重的 AVG 值
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
第二次尝试是选择值的总和将它们乘以它们的权重,然后将它们除以权重的总和。权重总和缺失。不知道怎么添加
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