Reputation: 2668
Currently i'm working on an app where i need to get average number of orders per week day per hour of the day and my code is like that
Spree::Order.group_by_day_of_week(:created_at, range: @start_date..@end_date, format: '%a').group_by_hour_of_day(:created_at, format: "%-l %P").count
I'm using groupdate gem
But this just count results. how can i get the average ?!
Upvotes: 0
Views: 156
Reputation: 11216
The average of a set of numbers is simply the sum of the numbers divided by the total number of values in the set.
Assuming your method chain returns hash where the values are integers, then this should be as simple as:
hash = Spree::Order
.group_by_day_of_week(:created_at, range: @start_date..@end_date, format: '%a')
.count
average = hash.values.sum.to_f / hash.count.to_f
You may or maynot want to convert integers to floats, but you probably will. If you end up with a number like:
average == 0.15728715728715728
You might want to round it to say 2 decimals
avearge.round(2)
=>0.16
I don't think you really want to do this .group_by_hour_of_day(:created_at, format: "%-l %P")
in the same chain, but probably a separate call chain for that, but I'm not sure.
Upvotes: 1