You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails按指定键统计Hash及按月分组时如何筛选2019年1月后数据

解决方案

推荐优先选择数据库层面过滤的方案,性能最优:

方案1:查询时直接过滤时间范围(推荐)

直接在ActiveRecord查询链中增加时间条件,从源头减少查询的数据量:

# 定义起始时间为2019年1月1日0点
start_time = Time.new(2019, 1, 1)
Companion.where(companion_type: 1)
         .joins(:tasks)
         .where(tasks: {status: 3})
         .where("created_at >= ?", start_time)
         .group_by_month(:created_at)
         .size

注意:如果created_at字段同时存在于companions和tasks两张表中,需要明确指定表名避免歧义,比如把条件改成where("tasks.created_at >= ?", start_time)即可。

方案2:对已拿到的Hash结果进行过滤

如果你已经获取了全量的统计Hash,不想再发起数据库查询,可以直接用Ruby的Hash筛选方法处理:

# 原查询获取全量统计结果
full_stat = Companion.where(companion_type: 1).joins(:tasks).where(tasks: {status: 3}).group_by_month(:created_at).size
# 筛选2019年1月及之后的结果
start_date = Date.new(2019, 1, 1)
filtered_stat = full_stat.select { |month, _| month >= start_date }

内容的提问来源于stack exchange,提问作者Noah_J.C_Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 08:42:02