【发布时间】: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