Repository is archived
No commit activity in last 3 years
No release in over 3 years
Perform weighted averages, even across associations. Rails 3 only because it uses ARel.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

Runtime

 Project Readme

weighted_average

Do weighted averages in ARel.

Rationale

You have a bunch of flight records with passenger count and distance.

  • Flight EWR <-> MSN; 30,000 passengers last month; 500 miles
  • Flight EWR <-> BOM; 15 passengers last month; 10,000 miles

The average distance is (10_000 + 500) / 2 = 5250.

The average distance weighted by passenger count is (30_000 * 500 + 15 * 10_000) / (10_500) = 1442.

Usage

Using FlightSegment from Brighter Planet's earth library:

>> FlightSegment.weighted_average(:distance, :weighted_by => :passengers)
=> 2436.1959

You can also see the SQL that is generated:

>> FlightSegment.weighted_average_relation(:distance, :weighted_by => :passengers).to_sql
=> "SELECT (SUM((`flight_segments`.`distance`) * `flight_segments`.`passengers`) / SUM(`flight_segments`.`passengers`)) AS weighted_average FROM `flight_segments` WHERE (`flight_segments`.`distance` IS NOT NULL)"

Copyright

Copyright (c) 2012 Brighter Planet, Inc.