2016-03-15 48 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

謝謝大家的幫助。是的,事實證明我所做的確是正確的。該數據集具有丟失的加權平均值丟失值。一旦我歸咎於這些,我就能夠得出正確的答案。在計算時會感到愚蠢的是錯過了那件重要的事情。