如何查找具有不同特定权重的多列的平均值?

时间:2015-05-18 10:51:43

标签: sql sql-server sum average weighted-average

我需要计算mssql中Value_AValue_BValue_C的平均值。
我的问题是我需要的每一个信息都在一行中。

每个价值都有自己的重量:

(sum of values * weight) / (sum weight):

每列都可以为null。如果有值而不是重量,则重量为100,
如果有重量但没有值,则当然不考虑具体值

e.g。

第1栏:

(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

2 个答案:

答案 0 :(得分:2)

这是你在找什么?

SELECT SUM(val * COALESCE(w, 100)) / SUM(w) as weighted_average,
       SUM(val * COALESCE(w, 100)) as weighted_sum
FROM table t CROSS APPLY
     (VALUES (t.VALUE_A, t.Weight_A),
             (t.VALUE_B, t.Weight_B),
             (t.VALUE_C, t.Weight_C)
     ) a(val, w)
WHERE a.val IS NOT NULL;

答案 1 :(得分:0)

这是平均值的计算方法

    SELECT *
        ,CASE 
            WHEN (W.weight_A + W.Weight_B+ W.Weight_C) = 0
                THEN 0
            ELSE (ISNULL(VALUE_A, 0 * W.Weight_A)
                  + (ISNULL(VALUE_B, 0) * W.Weight_B) 
                  + (ISNULL(VALUE_C, 0) * W.Weight_C)) 
                  / (W.weight_A + w.Weight_B+ W.Weight_C)
            END Average
FROM TABLE t
CROSS APPLY (Select CASE WHEN VALUE_A is null then 0 ELSE ISNULL(Weight_A,100) END [Weight_A]
            ,CASE WHEN VALUE_B is null then 0 ELSE ISNULL(Weight_B,100) END [Weight_B]
            ,CASE WHEN VALUE_C is null then 0 ELSE ISNULL(Weight_C,100) END [Weight_C]) W