0

我的表中有以下数据列(使用 Postgres):

occurred_at, name
2012-01-01, Ryan
2012-01-01, Ryan
2012-01-01, Mark
2012-01-01, Ryan
2012-01-01, Paul
2012-01-01, John
2012-02-01, Ryan
2012-02-01, Mark
2012-02-01, Ryan
2012-02-01, Mark
2012-02-01, Paul
2012-02-01, Kevin
2012-02-01, John
2012-03-01, Ryan
2012-03-01, Gary
2012-03-01, Ryan
2012-03-01, Mark
2012-03-01, Paul
2012-03-01, Kevin
2012-01-01, John

我要做的是按日期对名称进行分组并添加计数并将其输出到 json

{ date: 2012-01-01, ryan: 3, mark: 1, paul: 1, john: 1 },
{ date: 2012-02-01, ryan: 2, mark: 2, paul: 1, john: 1, kevin: 1 },
{ date: 2012-03-01, ryan: 2, mark: 1, paul: 1, john: 1, kevin: 1 }

到目前为止,我有以下代码:

# user controller
 def index
  @users = User.show_data
  render :json
end


# user model

def self.show_data(start = 14.months.ago)
    total_users = users_by_month(start)
    (start.to_date..Date.today).map do |date|
      {
        occurred_at: date,
        total_users[date].name.to_sym: total_users[count],
      }
    end
  end

  def self.users_by_month(start)
    users = where(occurred_at: start.beginning_of_day..Time.zone.now )
    users = users.group("date(occurred_at)")
    users = orders.select("occurred_at, count(name) as user_name")
    users.each_with_object({}) do |user, names|
       names[user.occurred_at.to_date] = user.user_name
    end
  end

大约有 200 万行,因此它需要是一个可扩展的选项。

提前致谢,

瑞安

4

1 回答 1

0

如果您需要这种更具可扩展性,您可能需要创建一个DATE类型列以用于分组并确保其上有索引。

您将使用此列代替DATE(occurred_at)您的计算。

请记住,此列应设置为回调处理程序occurred_at中的等效日期。before_save

于 2013-02-25T20:03:05.130 回答