单个查询中的MySQL加权平均值

时间:2013-06-26 12:01:02

标签: mysql sql

我有一个MySQL表,如下所示:

id  load_transit    load_standby    hours_transit   hours_standby
1   40              20              8               4
2   30              15              10              10
3   50              10              3               9

我需要做以下计算:

(中间计算)

hours_transit_total = 8+10+3 = 21
hours_standby_total = 4+10+9 = 23

(期望的结果)

load_transit_weighted_mean = 40*(8/21) + 30*(10/21) + 50*(3/21) = 36.667
load_standby_weighted_mean = 20*(4/23) + 15*(10/23) + 10*(9/23) = 13.913

是否可以在单个查询中执行此操作?最好的设计是什么?

2 个答案:

答案 0 :(得分:6)

请注意

40*(8/21) + 30*(10/21) + 50*(3/21) =
(40*8)/21 + (30*10)/21 + (50*3)/21 =
(40*8 + 30*10 + 50*3)/21

20*(4/23) + 15*(10/23) + 10*(9/23) =
(20*4)/23 + (15*10)/23 + (10*9)/23 =
(20*4 + 15*10 + 10*9)/23

允许您使用

获得所需的结果
SELECT sum(hours_transit * load_transit) / sum(hours_transit),
       sum(hours_standby * load_standby) / sum(hours_standby)
FROM your_table

答案 1 :(得分:0)

我刚才有同样的问题并建立了这个小问题,我认为如何在一个查询中找到加权平均值:

select sum(balance), sum(rate * balance / 5200) as weighted_rate, -- what I want
-- what you cannot do: sum(rate * balance / sum(balance))
sum(balance * rate) / sum(balance) as weighted_rate_legit -- ah thank you transitive math properties
from (
select '4600' as balance, '2.05' as rate from dual 
union all
select '600' as balance, '2.30' as rate from dual
) an_alias;