简体   繁体   中英

MySQL - two dependent weighted averages in a single query

This question extends a previous question . I want to add a weighted average total in addition to some individual weighted averages.

I have a MySQL table which looks like this:

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

I need to do the following calculations:

(intermediate calculations)

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

(new extra desired result)

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

Is it possible to do this in a single query? What would the best design be?

By extension of my answer to your previous question, this is just as simple:

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

Here is the corresponding sqlfiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM