1

我已经搜索了几个小时试图找到解决方案。

我对这个说法有疑问。它返回 nil 但它应该返回一个哈希值。

stats = stats.select("date, sum(attendance) as total_attendance")

我在我的控制台中运行它:

Stat.select("date, sum(attendance) as total_attendance")

这是控制台的输出:

Stat.select("date, sum(attendance) as total_attendance")
  Stat Load (0.3ms)  SELECT date, sum(attendance) as total_attendance FROM "stats"
 => #<ActiveRecord::Relation [#<Stat id: nil, date: "2013-01-06">]>

我正在寻找的结果将是带有 :date => value 和 :total_attendance => value 的哈希值

attendance: 31, date: "2013-06-30"

我也尝试过使用

Stat.group(:date).sum(:attendance)

但它返回一个哈希,其中日期为键,总出勤率为值。

像这样:

Sun, 06 Jan 2013=>66, Sun, 13 Jan 2013=>65

谁能告诉我我做错了什么?我认为第一个陈述是正确的,但最重要的是我正在寻找正确的结果。

4

1 回答 1

1

select语句需要几行结果,而sum它是一个计算并且只为整个表生成一个结果(如果没有where给出语句)。所以应该与类级别sum一起使用或直接使用:group

Stat.sum(:attendance)

更新:

要获得您想要的哈希,只需执行以下操作:

Stat.select('date, sum(attendance) as total_attendance').group(:date)

如果您不按日期分组,结果将不正确。

于 2013-07-20T04:56:35.253 回答