0

我需要在 mssql中计算Value_AValue_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
4

2 回答 2

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;
于 2015-05-18T10:58:27.680 回答
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
于 2015-05-18T10:58:53.513 回答