简体   繁体   中英

Rails advanced queries with join and sum calculation

I have two models: companies and expenses. Companies have many expenses and expenses belong to companies. My expense model has an 'amount' column.

I was wondering if there is a way to perform a find based on a date range and the amount column of the expenses. Something like top 3 companies by total expense amounts over a 7 day period.

I've tried for the better part of the day to get this to work, I've attempted joins, chaining named scopes, raw sql, etc. and I'm not having any luck.

Thanks for the help.

我将此添加到我的公司模型中,并且能够实现我所寻找的...

named_scope :top_with_expenses, :joins => :expenses, :conditions => ['expenses.created_at > ?', Time.now.midnight - 7.days], :order => "SUM(expenses) DESC", :group => "expenses.company_id", :limit => 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM