我與下面結構的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
感謝, 乙
您的查詢語法錯誤。你提供的結果是不正確的。我編輯了你的問題。也請提供所需的結果集,以便我們提供答案。 – FLICKER
你的邏輯對我來說看起來是正確的。你可以設置一個SQL小提琴嗎? –
@GordonLinoff感謝您的回覆。爲愚蠢的問題道歉,我如何在這裏設置一個SQL小提琴? – Bee