How can I? such as "select max(peak_kw) peak,month from sola_daylies group by month;"

89 views
Skip to first unread message

Winterboum

unread,
Jan 18, 2015, 8:37:37 AM1/18/15
to rubyonra...@googlegroups.com
When I tried on mysql
  select max(peak_kw) peak,month from sola_daylies group by month;
It returns as I expected
+--------+------------+
| peak   | month      |
+--------+------------+
| 0.2126 | 2014-12-01 |
| 1.6156 | 2015-01-01 |
+--------+------------+

on rails console,
  Sola::Dayly.find_by_sql("select max(peak_kw) peak,month from sola_daylies group by month")
log says, it makes sql command
  select max(peak_kw) peak,month from sola_daylies group by month
It returns without column "peak"
[#<Sola::Dayly id: nil, month: "2014-12-01">, #<Sola::Dayly id: nil, month: "2015-01-01">]

Sola::Dayly.select("max(peak_kw) peak",:month).group(:month)
returns same.

Daniel Loureiro

unread,
Jan 19, 2015, 3:55:31 PM1/19/15
to rubyonra...@googlegroups.com
Try this:

Sola::Dayly.group(:month).maximum(:peak_kw)


Explanation:
"find_by_sql" is to be used to get real records, not database calculations. The "Group", "Max" and other statements produce calculations, not real records.

If you want to do a raw SQL, do with "ActiveRecord::Base.connection.execute"

results = ActiveRecord::Base.connection.execute("select max(peak_kw) peak,month from sola_daylies group by month")

pp results
[0]

--
Daniel Loureiro

Winterboum

unread,
Jan 20, 2015, 5:47:02 AM1/20/15
to rubyonra...@googlegroups.com

Thank you,   I got it.

2015年1月20日火曜日 5時55分31秒 UTC+9 Daniel Loureiro:
Reply all
Reply to author
Forward
0 new messages