Reputation: 20835
Given that I have a Foo
model w/ the standard Rails timestamp columns what would be the most efficient way to calculate the average number of days between records being created?
Upvotes: 3
Views: 1254
Reputation: 99
If you use MySQL
secs = Foo.where("created_at IS NOT NULL").average("UNIX_TIMESTAMP(created_at)").to_i
DateTime.strptime secs.to_s, "%s"
Upvotes: 0
Reputation: 14881
The maximum
and minimum
class methods of your model will use the SQL aggregate functions min()
and max()
to find the extreme values efficiently.
span_secs = Foo.maximum(:created_at) - Foo.minimum(:created_at)
avg_secs = span_secs / (Foo.count - 1)
avg_days = avg_secs / (24 * 60 * 60)
Upvotes: 5