foo, foo_bar 表示为 ActiveModel 类
create table foo (id, captured_date)
create table foo_bars (id, foo_id, val1, val2)
insert into foo (1, '2012-11-01')
insert into foo (2, '2012-11-02')
insert into foo_bars (1, 1, 1, 1)
insert into foo_bars (1, 1, 2, 2)
insert into foo_bars (1, 2, 3, 3)
insert into foo_bars (1, 2, 4, 4)
我希望在表格中显示以下内容 (date, sum(val1), avg(val2))
2012-11-01 3 1.5
2012-11-02 7 3.5
_________________
10 2.5
_________________
上面是sum(val1), avg(val2) across dates
在您的 View 中使用 AR 查询实现此目的的最简单方法是什么。我的 View 代码应该是什么样子,我应该使用什么查询。
最佳答案
使用
select("date, SUM(val1) as sum_val1").group("date").pluck(:date, :sum_val1)
您只会得到一个总和数组。您可以根据需要添加字段。 另一个人提到的解决方案不是那么好,因为它在 Ruby 中而不是在 SQL 中进行求和。 要显示它真的很简单,它只是一个数组!显示 <%= result.inspect %> 并从那里开始。
关于mysql - 如何在 rails 中的几列上执行求和和平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13284726/