我有一个销售表,包含5列
id, sale_code, total_sale, created_at, updated_at
我想做一个这样的周报
date | total_sale
2016-09-27 | 1000
2016-09-28 | 0
2016-09-29 | 500
,当当天没有产品销售时,报告中仍然显示为0值。
有什么办法可以做到吗?提前感谢
您可以浏览当前一周的每一天,并计算当天的所有销售额。
它可能看起来像这样:
today = Date.today
week_days = (today.at_beginning_of_week..today.at_end_of_week).map
week_sales = Sales.where("created_at > ? AND created_at < ?", week_days.first.beginning_of_day, week_days.last.end_of_day)
p "date | total_sale"
week_days.each do |day|
day_sales = week_sales.count{|sale| sale.created_at > day.beginning_of_day && sale.created_at < day.end_of_day}
p "#{day.strftime("%Y-%m-%d")} | #{day_sales}"
end