mysql - 如何在 rails 中的几列上执行求和和平均

标签 mysql ruby-on-rails ruby-on-rails-3 activerecord

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/

相关文章:

php - 用文本链接在 MYSQL 中设置值?

php - 在 Laravel 查询中从另一个表中选择下一个数字

javascript - 具有唯一 ID 的 Rails 渲染格式 js

ruby-on-rails - Rails - 给定 @Comments - 如何获取倒数第二条评论而不重新访问数据库

ruby-on-rails-3 - 如何获得在rails应用程序中使用sendgrid发送的电子邮件的回复以保存在数据库中

mysql - SQL Join 2 tables 即使没有匹配的数据

mysql - 无法永久设置 UTC 时区

ruby-on-rails - Rails访问上传的文件并将其保存到PaperClip

mysql - 从 ActiveRecord::Relation 获取 SQL 数组

javascript - 使用 jQuery 显示前一个 td 元素