我在我的头上试图获得统计数据在n天的过程中。我不关心输出格式,只要它按顺序显示日期,并将值显示为数组... all_data查询(下面)将获得确定时间段内的所有值,但它赢得了'为没有值的日期创建行。目标是能够输出:填写空白日期的分组查询,返回一些空行
# Get 10 (for example) days of data->
[
{date:'datetime-day-ago-10', values: [{foo:'bar', foo2:'bar2', foo3:'bar'3}]}
{date:'datetime-day-ago-9', values: [{foo:'bar', foo2:'bar2', foo3:'bar'3}]}
{date:'datetime-day-ago-8', values: []}
{date:'datetime-day-ago-7', values: [{foo:'bar', foo2:'bar2', foo3:'bar'3}]}
{date:'datetime-day-ago-6', values: []}
{date:'datetime-day-ago-5', values: []}
{date:'datetime-day-ago-4', values: [{foo:'bar', foo2:'bar2', foo3:'bar'3}]}
{date:'datetime-day-ago-3', values: [{foo:'bar', foo2:'bar2', foo3:'bar'3}]}
{date:'datetime-day-ago-2', values: []}
{date:'datetime-day-ago-1', values: []}
]
这里是我在这里使用的方法。
def counts
from = params[:days].to_i.days.ago.to_time.beginning_of_day
to = 0.days.ago.to_time.end_of_day
all_data = current_user.values.all
.where(field_id: params[:field_id], created_at: from .. to)
.where.not(input: nil)
.order(input: :desc)
.group_by { |value| value['created_at'].to_date}
.map {|k,v| [k,v]}
grouped = (0..params[:days].to_i-1).to_a.inject([]) do |memo, i|
if all_data[i].present?
date = all_data[i][0].to_time
values = all_data[i][1].group_by { |value| value.input }.map { |k, v| {input:k, count:v.length} }.sort! { |x,y| x['input'] <=> y['input']}
total = 0
values.each do |value|
total = total + value[:count]
end
else
# This is where I can't figure out how to assign a date for rows which have no data.
date = ((i-params[:days].to_i+1)*-(1)).days.ago.beginning_of_day
end
memo << {'date': date, 'total': total || 0, 'values': values || []}
memo
end
grouped = grouped.sort_by { |day| day['date'] }
render json: grouped
end
# Sample of entire output for 10 days
0: {date: "2015-10-31T00:00:00.000-07:00", total: 15,…} <- 10-31-2015 HAS VALUES
1: {date: "2015-11-01T00:00:00.000-07:00", total: 49,…} <- 11-01-2015 HAS VALUES
2: {date: "2015-11-02T00:00:00.000-08:00", total: 10,…} <- 11-02-2015 HAS VALUES
3: {date: "2015-11-03T00:00:00.000-08:00", total: 21,…} <- 11-03-2015 HAS VALUES
4: {date: "2015-10-30T00:00:00.000-07:00", total: 0, values: []}
5: {date: "2015-10-31T00:00:00.000-07:00", total: 0, values: []} \
6: {date: "2015-11-01T00:00:00.000-07:00", total: 0, values: []} - No matter what I try I can't get these dates to be the 5 days before 10-31-2015...
7: {date: "2015-11-02T00:00:00.000-08:00", total: 0, values: []}/
8: {date: "2015-11-03T00:00:00.000-08:00", total: 0, values: []}
9: {date: "2015-11-04T00:00:00.000-08:00", total: 0, values: []} <- 11-04-2015 This should appear up there^under the last HAS VALUES row
那么,如何正确地创建空值行的日期?然后,我怎样才能确保它们落入正确的顺序?就像我说过的,我对此感到头痛。算法不是我的一杯茶。