如何查询表col的多个值

我是唐尼

我做了一件可怕的事...

我有一个包含帐户余额的表格。它具有account_id,金额和month_end日期的属性。我想查询该表以获取过去十二个月的余额。但是,没有比这更好的方法了。

scope :recent_balances, lambda { { :conditions => 
  ["month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ? OR month_end = ?", 
  last_month_end.to_s, 
  (last_month_end-1.month).end_of_month.to_s,
  (last_month_end-2.month).end_of_month.to_s,
  (last_month_end-3.month).end_of_month.to_s,
  (last_month_end-4.month).end_of_month.to_s,
  (last_month_end-5.month).end_of_month.to_s,
  (last_month_end-6.month).end_of_month.to_s,
  (last_month_end-7.month).end_of_month.to_s,
  (last_month_end-8.month).end_of_month.to_s,
  (last_month_end-9.month).end_of_month.to_s,
  (last_month_end-10.month).end_of_month.to_s,
  (last_month_end-11.month).end_of_month.to_s ] } }

private

def self.last_month_end
  last_month_end ||= (Date.today - 1.month).end_of_month
end

我的问题是:

  1. 进行此查询的聪明方法是什么?(这绝对不是我刚想到的。)
  2. 如何修改此查询以使其更灵活?我希望能够将特定的月份数传递给查询(例如,查询余额为六个月或余额为24个月的查询)
中提琴
months = (1..11).map { |m| last_month_end.advance(months: 0 - m) }

where("month_end IN (?)", months)

或类似的东西。这将是您进行上述操作时更具可读性和可维护性的方式。就像其他人所说的,您可以检查SQL中的日期是否在开始日期和结束日期之间。

where("date >= ? AND date <= ?", start_date, end_date)

或(更好)

where("date BETWEEN ? AND ?", start_date, end_date)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章