sql - 使用 ActiveRecord 获取一系列有条件的计数

标签 sql ruby-on-rails ruby activerecord

我正在显示一个 Subscription 计数的图表,这些计数可能在某个时候被 soft_destroyed_at

为此,我每个月都运行一次查询,这当然不如一个大查询好,但我的 SQL 技能又一次让我失望了。

这是我在 Ruby 中的做法:

months = (0..12).map { |i| i.months.ago.end_of_month }

stats = Hash[months.map do |eom|
  [
    eom.beginning_of_month.to_date,
    Subscription.where(
      'created_at < ?' \
      'AND (soft_destroyed_at IS NULL ' \
      '  OR soft_destroyed_at > ?) ' \
      'AND (suspended_at IS NULL ' \
      '  OR suspended_at > ?)',
      eom, eom, eom
    ).count
  ]
end]

# => { 2018-04-01 => 10, 2018-03-01 => 15, ... }

我如何使用 ActiveRecord 将其写成一个查询——或者在必要时使用原始 SQL>

数据库是 Postgres 10.2,应用程序是 Rails 5.2。

谢谢!

最佳答案

你可以使用这个查询(我在 2017 年使用了 12 个月;随意更改)。正如您在评论中所说,这假设一个 Postgresql 数据库:

query = 
  "select months.month, count(created_at) "\
  "from "\
    "(select DATE '2017-01-01'+(interval '1' month * generate_series(0,11)) as month, "\
            "DATE '2017-02-01'+(interval '1' month * generate_series(0,11)) as next) months "\
    "outer join subscriptions on "\
    "created_at < month and "\
    "(soft_destroyed_at IS NULL or soft_destroyed_at >= next) and "\
    "(suspended_at IS NULL OR suspended_at >= next) "\
  "group by month "\
  "order by month"

results = ActiveRecord::Base.connection.execute(query)

第一个子查询(from 中的 select)生成如下:

month                 next
"2017-01-01 00:00:00";"2017-02-01 00:00:00"
"2017-02-01 00:00:00";"2017-03-01 00:00:00"
"2017-03-01 00:00:00";"2017-04-01 00:00:00"
"2017-04-01 00:00:00";"2017-05-01 00:00:00"
"2017-05-01 00:00:00";"2017-06-01 00:00:00"
"2017-06-01 00:00:00";"2017-07-01 00:00:00"
"2017-07-01 00:00:00";"2017-08-01 00:00:00"
"2017-08-01 00:00:00";"2017-09-01 00:00:00"
"2017-09-01 00:00:00";"2017-10-01 00:00:00"
"2017-10-01 00:00:00";"2017-11-01 00:00:00"
"2017-11-01 00:00:00";"2017-12-01 00:00:00"
"2017-12-01 00:00:00";"2018-01-01 00:00:00"

Next 仅用于更轻松地检查订阅是否至少在下个月之前处于事件状态(销毁或暂停是 >= next(保证订阅者在当月处于事件状态)。

关于sql - 使用 ActiveRecord 获取一系列有条件的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029438/

相关文章:

sql - block 过程 PL/SQL 与 Oracle

ruby-on-rails - Learn Enough Setup 的 Ruby 安装失败 - Puma gem 安装错误,Mac Sierra

sql - PGError : ERROR: column "is_required" is of type boolean but expression is of type integer

ruby-on-rails - Mandrill raw_message 中的额外 "\n "破坏了一些链接

Ruby Selenium Webdriver - 页面重定向(刷新)时需要等待/休眠

ruby-on-rails - 有没有一种方法可以添加到数据库列中的现有余额或金额,而无需在更新时替换它?

python - 在 Ruby 中检查变量类型

php - MySQL 和 PHP,比较两个表,获取日期并赋值

sql - 如何选择SQL数据库表中带有分隔值的字段中的第n个项目?

sql - 操作 phpBB 标记所需的 TSQL 正则表达式函数