【问题标题】:Rails3/ActiveRecord: Change existing query to group by monthsRails3/ActiveRecord:将现有查询更改为按月分组
【发布时间】:2011-04-20 14:07:44
【问题描述】:

模型入口.rb

def self.calculate(year, month, id)
     where(':id = entries.user_id', {    
          :id => id
     }).
     where('entries.date <= :last_day', { 
          :last_day => Date.new(year, month, 1).at_end_of_month
     }).
     select('sum(case when joint = "f" then amount_calc else 0 end) as sum_single,' + 
            'sum(case when joint = "t" then amount_calc else 0 end) as sum_joint,' + 
            'sum(case when compensation = "t" then amount_calc else 0 end) as sum_compensation')
  end

查询为特定用户和给定月份的所有条目提供三个总和。到目前为止工作正常。

接下来我真正需要的是完全相同的,但每个月都有一个值(并且不同年份的月份必须在不同的组中)。 代码需要同时使用 SQLite 和 PostgreSQL。

{ 附加问题:是否可以像我上面的原始代码中的 ONE 查询一样获得分组和总和?我相信这是不可能的...... }

【问题讨论】:

  • 我认为 sqlite 和 postgre 中的 Date 函数有不同的语法,因此您不能将其包装在一个查询中。你应该先检查适配器
  • 我真的希望两个数据库都有一个解决方案。如何根据模型中的适配器切换查询?
  • 你可以试试这个ActiveRecord::Base.configurations[Rails.env]['adapter']
  • 如果语法不同,就不可能有一个解决方案。

标签: sql ruby-on-rails-3 sqlite postgresql activerecord


【解决方案1】:

SQLite

def self.calculate(year, month, id)
 where(':id = entries.user_id', {    
      :id => id
 }).
 where('entries.date <= :last_day', { 
      :last_day => Date.new(year, month, 1).at_end_of_month
 }).
 select('sum(case when joint = "f" then amount_calc else 0 end) as sum_single,' + 
        'sum(case when joint = "t" then amount_calc else 0 end) as sum_joint,' + 
        'sum(case when compensation = "t" then amount_calc else 0 end) as sum_compensation').
 group("strftime('%Y-%m', created_at)")
end

Postgre 这样的东西(我从来没有用过这个数据库)

def self.calculate(year, month, id)
 where(':id = entries.user_id', {    
      :id => id
 }).
 where('entries.date <= :last_day', { 
      :last_day => Date.new(year, month, 1).at_end_of_month
 }).
 select('sum(case when joint = "f" then amount_calc else 0 end) as sum_single,' + 
        'sum(case when joint = "t" then amount_calc else 0 end) as sum_joint,' + 
        'sum(case when compensation = "t" then amount_calc else 0 end) as sum_compensation').
 group("EXTRACT(YEAR FROM TIMESTAMP created_at)||EXTRACT(MONTH FROM TIMESTAMP created_at)")
end

所以你应该首先检查使用了什么适配器,然后使用其中一个查询

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2014-01-12
    • 2014-10-24
    相关资源
    最近更新 更多