我正在显示一个 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/