用标准SQL计算加权平均值

时间:2016-03-15 18:15:04

标签: sql sql-server

我有一个SQL Server表,其结构如下:

      model term transaction str_weight
      750i    36    L        2
      750i    39    L        3
      750i    48    D        3
      750i    39    L        3
      750i    48    L        3

我需要在SQL中按事务计算加权平均值,并以下面的格式显示:

     model L_Term   D_Term D_L_Term 
     750i    48      36     48            (not accurate values)      

这是我到目前为止所做的,它给了我不正确的结果。 谁能指出我做错了什么?在sql中做任何更好的方法来衡量平均值?

select model
 , sum(str_weight) as TotalWeight           
 , sum(case when [transaction] = 'D' then Term*str_weight end)/sum(case when [transaction] = 'D' then str_weight else 0.0 end) as Weighted_D_Term
 , sum(case when [transaction] = 'L' then Term*str_weight end)/sum(case when [transaction] = 'L' then str_weight else 0.0 end) as Weighted_L_Term
 , sum(case when [transaction] = 'D' OR [transaction] = 'L' then Term*str_weight end)/sum(case when [transaction] = 'D' OR [transaction] = 'L' then str_weight else 0.0 end) Weighted_DL_Term
from model_weights
group by model

谢谢, 乙

2 个答案:

答案 0 :(得分:1)

这是一个有效的例子。它与您在问题中提供的内容没有什么不同,除非它包含您在问题中推断的详细信息。

给定公式:总和(期限*权重)/总和(权重)

以下查询:

create table #temp (model varchar(10), term int, [transaction] char(1), str_weight float)

insert into #temp values
('750i', 36, 'L', 2),
('750i', 39, 'L', 3),
('750i', 48, 'D', 3),
('750i', 39, 'L', 3),
('750i', 48, 'L', 3)

select model
      ,sum(str_weight) as TotalWeight
      ,isnull(sum(case when [transaction] = 'D' then term * str_weight end) / sum(case when [transaction] = 'D' then str_weight end), 0.00) as Weighted_D_Term
      ,isnull(sum(case when [transaction] = 'L' then term * str_weight end) / sum(case when [transaction] = 'L' then str_weight end), 0.00) as Weighted_L_Term
      ,isnull(sum(case when [transaction] in ('D', 'L') then term * str_weight end) / sum(case when [transaction] in ('D', 'L') then str_weight end), 0.00) as Weighted_D_L_Term
from   #temp
group by model

drop table #temp

产生此数据集:

model      TotalWeight   Weighted_D_Term   Weighted_L_Term   Weighted_D_L_Term
---------- ------------- ----------------- ----------------- -------------------
750i       14            48                40.9090909090909  42.4285714285714

这不准确吗?如果是这样,你有什么不同的期望?如果这不是你得到的,那么你在问题中没有提供的SQL部分中还有其他东西正在改变输出。

答案 1 :(得分:0)

感谢大家的帮助。是的,事实证明我正在做的事情确实是正确的。数据集具有丢失的值,这些值会使加权平均值失效。一旦我估算了那些,我就能得出正确的答案。感到愚蠢,因为在计算时错过了这个重要的部分。