Rails3/ActiveRecord:将现有查询更改为按月分组
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 一起使用。
{ 附加问题:是否可以像上面在一个查询中的原始代码一样获得分组和总和?我相信这是不可能的...}
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
The query delivers three sums for a particular user and all entries up to the given month. Works fine so far.
What I really would need next is exactly the same but with one value for each month (and months in different years have to be in a different group). The code needs to work with both SQLite and PostgreSQL.
{ Additional question: is it possible to get the grouping and the overall sums like in my original code above in ONE query? I believe it is not possible... }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQLite
Postgre 像这样(我从未使用过这个数据库)
所以你应该首先检查使用了什么适配器,然后使用这些查询之一
SQLite
Postgre something like this (I've never used this db)
So you should firstly check what adapter is used and then use one of those queries