ac360
ac360

Reputation: 211

Get average for only a certain date range

In a database with hourly trade prices for the last ten years, the following query will group prices by day, produce a daily average price, and return the average price for every day in the DB:

Trade.average(:price, :group => "DATE_TRUNC('day', date)")

But, this will return an excessively large response, and I only need to get average prices for the last 7 days. What can I add to this query to only perform the averaging for the last 7 days of data as given in the date column?

Upvotes: 2

Views: 223

Answers (1)

Mischa
Mischa

Reputation: 43298

Something like this should work:

Trade.where('date >= ?', 7.days.ago).average(:price, :group => "DATE_TRUNC('day', date)")

Upvotes: 4

Related Questions