0

I am trying to write following SQL in rails (via ActiveRecord) and having no luck. SQL is following end as such works:

select main_section_id, district_id, sum(answer)
from section_inputs
where year = 2012
and main_section_id= 2 
group by main_section_id, district_id 
order by 3 desc
limit 5

I think that column names are descriptive, in any case following Rails conventions. To sum the problem up, I am trying to get top 5 Districts for specific MainSection, answer column here is integer which represents my score system.

I know question is little too specific (doing my job for me), but I really hit the wall here and if asking for solution is too much some guidance would be great help as well.

Thanks

4

1 に答える 1

2

これはうまくいくはずです

SectionInput.select([:main_section_id, :district_id, 'sum(answer) as  total']).where(:year=>2012).where(:main_section_id=>2).group(:main_section_id).group(:district_id).order('3 desc').limit(5)

それ以外の場合は、実行するSQLを直接含めることができます

SectionInput.find_all_by_sql('select main_section_id, district_id,
sum(answer) from section_inputs where year = 2012 and main_section_id=
2  group by main_section_id, district_id  order by 3 desc limit 5')

また、ガイドを参照して、Rails 3 クエリの基本をすべて確認してください。

于 2013-01-05T14:02:35.077 に答える