1
我正在嘗試在ActiveRecord 4中編寫此查詢,但無濟於事。ActiveRecord從組中獲取平均值
SELECT date, AVG(gain) AS avg_gain FROM counters WHERE (date > '2014-03-03' ) GROUP BY date ORDER BY date DESC;
所以我炒了一起:
Counter.select("date, AVG(gain) as avg_gain").where("date > '2014-03-03'").group(:date).order(date: :desc)
=> #<ActiveRecord::Relation [#<Counter id: nil, date: "2014-04-01">, #<Counter id: nil, date: "2014-03-31">, #<Counter id: nil, date: "2014-03-30">, #<Counter id: nil, date: "2014-03-29">, #<Counter id: nil, date: "2014-03-28">, #<Counter id: nil, date: "2014-03-27">, #<Counter id: nil, date: "2014-03-26">, #<Counter id: nil, date: "2014-03-25">, #<Counter id: nil, date: "2014-03-24">, #<Counter id: nil, date: "2014-03-23">, ...]>
唯一的麻煩是,該結果不包含avg_gain
列。有任何想法嗎?
有什麼辦法,我可以掐出來?像'Counter.select(「date,AVG(gain)as avg_gain」)。其中(「date>'2014-03-03'」)。group(:date).order(date::desc).pluck(:日期,「avg_gain」)'? –
@JanNetherdrake你可以做'result.map {| counter | [counter [:date],counter [:avg_gain]]}'返回像[[[date,avg],[date,avg],...] – MrYoshiji