【问题标题】:Find records created in last 3 months in rails在 Rails 中查找过去 3 个月内创建的记录
【发布时间】:2020-08-17 16:30:48
【问题描述】:

下面是查询过去三个月每个月创建的代理数量。

agents_per_month = Agents.where("created_at > ? AND created_at < ?", Date.today.at_beginning_of_month - 2.months, Date.today).group("date_trunc('month', created_at)").count

结果输出如下:

{2020-07-01 00:00:00 UTC=>75, 2020-08-01 00:00:00 UTC=>31}

上述结果的问题是,自上个第三个月以来没有创建任何代理,因此它没有显示任何价值。但我希望它按以下顺序显示结果:

{2020-06-01 00:00:00 UTC=>0, 2020-07-01 00:00:00 UTC=>75, 2020-08-01 00:00:00 UTC=>31}

因此,如果一个月没有任何值,它应该显示 0,而不是特定月份没有值显示。

请帮我解决这个问题。

【问题讨论】:

  • 您只想要一个 activerecord 解决方案,还是考虑一个纯 SQL 查询?
  • @GMB 主动记录解决方案

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

您可以使用 PostgreSQL 加入 generate_series 表:

class Agent < ApplicationRecord

  def self.totals_in_last_three_months
    joins("
      RIGHT JOIN generate_series(
        date_trunc('month', statement_timestamp() - interval'2 months'),
        date_trunc('month', statement_timestamp()),
        interval'1 month'
      ) as months(month)
      ON date_trunc('month', agents.created_at) = months.month")
      .group('months.month')
      .count('agents.*')
  end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多