此问题扩展为previous question。除了某些加权平均值之外,我还要添加加权平均总数。
我有一个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
hours_total = 21+23 = 44
(新的额外预期结果)
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
load_total_weighted_mean = 36.667*(21/44)+13.913*(23/44) = 24.772
是否可以在单个查询中执行此操作?最好的设计是什么?
答案 0 :(得分:2)
通过扩展我对上一个问题的回答,这很简单:
SELECT sum(hours_transit * load_transit) / sum(hours_transit),
sum(hours_standby * load_standby) / sum(hours_standby),
(sum(hours_transit * load_transit + hours_standby * load_standby)) / sum(hours_transit + hours_standby)
FROM table1