【发布时间】:2014-05-21 11:04:35
【问题描述】:
我一直在我的 Rails 代码中使用 sql 查询,需要将其转换为 Active Record Query。我之前没有使用过 Active Record,所以我尝试通过 http://guides.rubyonrails.org/active_record_querying.html 来获得正确的语法,以便能够切换到这种获取数据的方法。我能够将简单的查询转换成这种格式,但还有其他复杂的查询,比如
SELECT b.owner,
Sum(a.idle_total),
Sum(a.idle_monthly_usage)
FROM market_place_idle_hosts_summaries a,
(SELECT DISTINCT owner,
hostclass,
week_number
FROM market_place_idle_hosts_details
WHERE week_number = '#{week_num}'
AND Year(updated_at) = '#{year_num}') b
WHERE a.hostclass = b.hostclass
AND a.week_number = b.week_number
AND Year(updated_at) = '#{year_num}'
GROUP BY b.owner
ORDER BY Sum(a.idle_monthly_usage) DESC
我需要 Active Record 格式,但由于复杂性,我不知道如何进行转换。
查询的输出是这样的
+----------+-------------------+---------------------------+
| owner | sum(a.idle_total) | sum(a.idle_monthly_usage) |
+----------+-------------------+---------------------------+
| abc | 485 | 90387.13690185547 |
| xyz | 815 | 66242.01857376099 |
| qwe | 122 | 11730.609939575195 |
| asd | 80 | 9543.170425415039 |
| zxc | 87 | 8027.090087890625 |
| dfg | 67 | 7303.070011138916 |
| wqer | 76 | 5234.969814300537 |
【问题讨论】:
标签: sql ruby-on-rails activerecord active-record-query