Reputation: 211
I have Rails app with a PostgreSQL DB Sales Table that looks like this:
Sales
price(decimal) date(datetime)
100.20 11/25/2012 11:00:00
30.43 11/26/2012 03:00:00
124.43 11/25/2012 18:00:00
190.34 11/26/2012 22:00:00
The DB has thousands of records like this, spanning 10 years.
I need to find the average sales price for each day and save each as a separate record in another DB table via a rake task.
For further clarity, Sales need to be grouped by day (even though data is in datetime format), and then the price values for that day need to be averaged.
Since I have 10 years of days, the ability to loop through each daily group and perform the averages is essential.
Does anyone have any suggestions as to how to write this?
Upvotes: 1
Views: 535
Reputation: 19879
You'll need to double check the syntax, but something like this should do it all in the database...
Sales.average(:price, :group => "DATE_TRUNC('day', date)")
Note that DATE_TRUNC is PG specific.
Upvotes: 3