Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Aircraft.average(:seats) versus Aircraft.weighted_average(:seats, :weighted_by => :takeoffs)

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .yardopts
Octocat-spinner-32 CHANGELOG
Octocat-spinner-32 Gemfile
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.markdown
Octocat-spinner-32 Rakefile
Octocat-spinner-32 weighted_average.gemspec
README.markdown

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.

Something went wrong with that request. Please try again.