2016-03-15 46 views
-1

我与下面结构的SQL Server表:计算加权平均值与标准SQL

 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 

感谢, 乙

+0

您的查询语法错误。你提供的结果是不正确的。我编辑了你的问题。也请提供所需的结果集,以便我们提供答案。 – FLICKER

+0

你的逻辑对我来说看起来是正确的。你可以设置一个SQL小提琴吗? –

+0

@GordonLinoff感谢您的回复。为愚蠢的问题道歉,我如何在这里设置一个SQL小提琴? – Bee

回答

1

这里的工作的例子。这与你在问题中提供的内容没有什么不同,只是它包含了在你的问题中推断出的细节。

给出的公式:总和(术语*重量)/ SUM(重量)

以下查询:

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部分还有一些其他内容正在改变输出。

+0

只需删除所有'else'部分,您就不必关心“除以零”。顺便说一句,这是完全一样的原始查询... – dnoeth

+0

@ dnoeth - 好建议,我知道它是完全一样的,这就是为什么我说这是*没有不同*。但是,这个查询的输出与OP的样本数据有很大不同。所以,问题中的查询不会创建数据集。这意味着他们省略了错误的SQL。也许最好是编辑OP的问题并包含'#temp'表代码。但那会改变他们的问题,我认为我们不应该这样做。 –

0

谢谢大家的帮助。是的,事实证明我所做的确是正确的。该数据集具有丢失的加权平均值丢失值。一旦我归咎于这些,我就能够得出正确的答案。在计算时会感到愚蠢的是错过了那件重要的事情。