ac360
ac360

Reputation: 211

Receive all values within a day & create average

I have a date(type:DateTime) column and a price(type:Decimal) column within my db. Records are created and saved hourly. I need to create a rake task to go through all of my stored data and create an average price for each day.

Using ActiveRecord, how can I query all of my records, group together all records within each day, create a new average price from those 24 records, and save it as a new record in a different table?

I imagine it would be something like this psuedocode:

Sales.all
  loop through them and group records by day
    loop through each grouping and create average
      average = DailyAverage.create

FYI I have about 10,000 records.

Upvotes: 0

Views: 366

Answers (1)

Alex Teut
Alex Teut

Reputation: 844

Scope is nice way to select some records and group them. In Sales class define something like scope :by_date, ->(needful_date) { where{ date == needful_date} }. Then in another model(which relates to another table) define your calculations:

def calculate_average_prices
  first_sale_date = # find your first sale date
  date_range = first_sale_date..Date.today
  grouped_sales = date_range.map{|date| Sales.by_date(date)}
  average_prices = grouped_sales.map do |sales|
    sales.map{|sale| sale.price.to_f}.average
  end
  # save your average prices
end

It's just an idea of solution. You'd better understand it and implement yourself.

Upvotes: 1

Related Questions