model entry.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。
{附加问题:是否有可能在上面的一个查询中获得上面的原始代码中的分组和总和?我相信这是不可能的......}
答案 0 :(得分: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
因此,您应首先检查使用的适配器,然后使用其中一个查询