sql - 使用 group by 子句选择最旧的 HABTM 记录
问题描述
我想在管理页面(使用chartkick)上显示一个折线图,其中包含与其最早导出日期相关的分数增量。
我有以下型号:
# score.rb
class Score < ApplicationRecord
has_and_belongs_to_many :export_orders, join_table: :scores_export_orders
end
# export_order.rb
class ExportOrder < ApplicationRecord
has_and_belongs_to_many :scores, join_table: :scores_export_orders
end
Score
对于每个至少有一个,我如何选择与最早ExportOrder
的对应(仅日期格式)?ExportOrder
created_at
我看过this,但我的情况是HABTM关系而不是简单的has_many。
我尝试了这段代码,以获得至少最旧的导出日期和分数数量之间的映射:
sql = "
SELECT
COUNT(DISTINCT scores.id), MIN(export_orders.created_at::date)
FROM
scores
INNER JOIN
scores_export_orders
ON
scores.id = scores_export_orders.score_id
INNER JOIN
export_orders
ON
export_orders.id = scores_export_orders.export_order_id
GROUP BY
export_orders.created_at::date
".split("\n").join(' ')
query = ActiveRecord::Base.connection.execute(sql)
query.map { |v| [v['count'], v['min']] }
但总分数大于所有具有导出日期的分数。有任何想法吗?
解决方案
尝试:
class Score < ApplicationRecord
has_and_belongs_to_many :export_orders, join_table: :scores_export_orders
def earliest_export_date
export_orders.pluck(&:created_at).min
end
end
这将让您调用@score.earliest_export_date
,它应该返回您想要的值。
我也认为这是在 ruby 中执行此操作的最高效方式,尽管有人可能会纠正我。
推荐阅读
- objective-c - 哪个更快?切换语句或字典?
- python - 未找到 Jupyter 实验室
- html - HTML - 最大宽度之外的 div
- mysql - 从 Latin1 SQL Server 迁移到 utf8mb4 MySQL 错误字符串错误问题
- java - 如何停止在java中打印空矩阵
- python - 在调用检查函数的函数中,应该在哪里生成/打印/发送错误消息?
- svg - 有没有办法绘制形状,以便它们的填充在组内充当不透明但对背景透明
- reactjs - 如何暂停 requestAnimationFrame 并在特定时间恢复(在 React 中)?
- recursion - 以队列为参数的递归空间复杂度
- wpf - 使用 Prism 7.x 和 8.x 在对话框中控制焦点?